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 Mock - a framework for writing C++ mock classes.
31//
32// This file defines some utilities useful for implementing Google
33// Mock.  They are subject to change without notice, so please DO NOT
34// USE THEM IN USER CODE.
35
36// IWYU pragma: private, include "gmock/gmock.h"
37// IWYU pragma: friend gmock/.*
38
39#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
41
42#include <stdio.h>
43
44#include <ostream>  // NOLINT
45#include <string>
46#include <type_traits>
47#include <vector>
48
49#include "gmock/internal/gmock-port.h"
50#include "gtest/gtest.h"
51
52namespace testing {
53
54template <typename>
55class Matcher;
56
57namespace internal {
58
59// Silence MSVC C4100 (unreferenced formal parameter) and
60// C4805('==': unsafe mix of type 'const int' and type 'const bool')
61#ifdef _MSC_VER
62#pragma warning(push)
63#pragma warning(disable : 4100)
64#pragma warning(disable : 4805)
65#endif
66
67// Joins a vector of strings as if they are fields of a tuple; returns
68// the joined string.
69GTEST_API_ std::string JoinAsKeyValueTuple(
70    const std::vector<const char*>& names, const Strings& values);
71
72// Converts an identifier name to a space-separated list of lower-case
73// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
74// treated as one word.  For example, both "FooBar123" and
75// "foo_bar_123" are converted to "foo bar 123".
76GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
77
78// GetRawPointer(p) returns the raw pointer underlying p when p is a
79// smart pointer, or returns p itself when p is already a raw pointer.
80// The following default implementation is for the smart pointer case.
81template <typename Pointer>
82inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
83  return p.get();
84}
85// This overload version is for std::reference_wrapper, which does not work with
86// the overload above, as it does not have an `element_type`.
87template <typename Element>
88inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
89  return &r.get();
90}
91
92// This overloaded version is for the raw pointer case.
93template <typename Element>
94inline Element* GetRawPointer(Element* p) {
95  return p;
96}
97
98// Default definitions for all compilers.
99// NOTE: If you implement support for other compilers, make sure to avoid
100// unexpected overlaps.
101// (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)
102#define GMOCK_INTERNAL_WARNING_PUSH()
103#define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)
104#define GMOCK_INTERNAL_WARNING_POP()
105
106#if defined(__clang__)
107#undef GMOCK_INTERNAL_WARNING_PUSH
108#define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")
109#undef GMOCK_INTERNAL_WARNING_CLANG
110#define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \
111  _Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))
112#undef GMOCK_INTERNAL_WARNING_POP
113#define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")
114#endif
115
116// MSVC treats wchar_t as a native type usually, but treats it as the
117// same as unsigned short when the compiler option /Zc:wchar_t- is
118// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
119// is a native type.
120#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
121// wchar_t is a typedef.
122#else
123#define GMOCK_WCHAR_T_IS_NATIVE_ 1
124#endif
125
126// In what follows, we use the term "kind" to indicate whether a type
127// is bool, an integer type (excluding bool), a floating-point type,
128// or none of them.  This categorization is useful for determining
129// when a matcher argument type can be safely converted to another
130// type in the implementation of SafeMatcherCast.
131enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
132
133// KindOf<T>::value is the kind of type T.
134template <typename T>
135struct KindOf {
136  enum { value = kOther };  // The default kind.
137};
138
139// This macro declares that the kind of 'type' is 'kind'.
140#define GMOCK_DECLARE_KIND_(type, kind) \
141  template <>                           \
142  struct KindOf<type> {                 \
143    enum { value = kind };              \
144  }
145
146GMOCK_DECLARE_KIND_(bool, kBool);
147
148// All standard integer types.
149GMOCK_DECLARE_KIND_(char, kInteger);
150GMOCK_DECLARE_KIND_(signed char, kInteger);
151GMOCK_DECLARE_KIND_(unsigned char, kInteger);
152GMOCK_DECLARE_KIND_(short, kInteger);           // NOLINT
153GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
154GMOCK_DECLARE_KIND_(int, kInteger);
155GMOCK_DECLARE_KIND_(unsigned int, kInteger);
156GMOCK_DECLARE_KIND_(long, kInteger);                // NOLINT
157GMOCK_DECLARE_KIND_(unsigned long, kInteger);       // NOLINT
158GMOCK_DECLARE_KIND_(long long, kInteger);           // NOLINT
159GMOCK_DECLARE_KIND_(unsigned long long, kInteger);  // NOLINT
160
161#if GMOCK_WCHAR_T_IS_NATIVE_
162GMOCK_DECLARE_KIND_(wchar_t, kInteger);
163#endif
164
165// All standard floating-point types.
166GMOCK_DECLARE_KIND_(float, kFloatingPoint);
167GMOCK_DECLARE_KIND_(double, kFloatingPoint);
168GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
169
170#undef GMOCK_DECLARE_KIND_
171
172// Evaluates to the kind of 'type'.
173#define GMOCK_KIND_OF_(type)                   \
174  static_cast< ::testing::internal::TypeKind>( \
175      ::testing::internal::KindOf<type>::value)
176
177// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
178// is true if and only if arithmetic type From can be losslessly converted to
179// arithmetic type To.
180//
181// It's the user's responsibility to ensure that both From and To are
182// raw (i.e. has no CV modifier, is not a pointer, and is not a
183// reference) built-in arithmetic types, kFromKind is the kind of
184// From, and kToKind is the kind of To; the value is
185// implementation-defined when the above pre-condition is violated.
186template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
187using LosslessArithmeticConvertibleImpl = std::integral_constant<
188    bool,
189    // clang-format off
190      // Converting from bool is always lossless
191      (kFromKind == kBool) ? true
192      // Converting between any other type kinds will be lossy if the type
193      // kinds are not the same.
194    : (kFromKind != kToKind) ? false
195    : (kFromKind == kInteger &&
196       // Converting between integers of different widths is allowed so long
197       // as the conversion does not go from signed to unsigned.
198      (((sizeof(From) < sizeof(To)) &&
199        !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
200       // Converting between integers of the same width only requires the
201       // two types to have the same signedness.
202       ((sizeof(From) == sizeof(To)) &&
203        (std::is_signed<From>::value == std::is_signed<To>::value)))
204       ) ? true
205      // Floating point conversions are lossless if and only if `To` is at least
206      // as wide as `From`.
207    : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
208    : false
209    // clang-format on
210    >;
211
212// LosslessArithmeticConvertible<From, To>::value is true if and only if
213// arithmetic type From can be losslessly converted to arithmetic type To.
214//
215// It's the user's responsibility to ensure that both From and To are
216// raw (i.e. has no CV modifier, is not a pointer, and is not a
217// reference) built-in arithmetic types; the value is
218// implementation-defined when the above pre-condition is violated.
219template <typename From, typename To>
220using LosslessArithmeticConvertible =
221    LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
222                                      GMOCK_KIND_OF_(To), To>;
223
224// This interface knows how to report a Google Mock failure (either
225// non-fatal or fatal).
226class FailureReporterInterface {
227 public:
228  // The type of a failure (either non-fatal or fatal).
229  enum FailureType { kNonfatal, kFatal };
230
231  virtual ~FailureReporterInterface() {}
232
233  // Reports a failure that occurred at the given source file location.
234  virtual void ReportFailure(FailureType type, const char* file, int line,
235                             const std::string& message) = 0;
236};
237
238// Returns the failure reporter used by Google Mock.
239GTEST_API_ FailureReporterInterface* GetFailureReporter();
240
241// Asserts that condition is true; aborts the process with the given
242// message if condition is false.  We cannot use LOG(FATAL) or CHECK()
243// as Google Mock might be used to mock the log sink itself.  We
244// inline this function to prevent it from showing up in the stack
245// trace.
246inline void Assert(bool condition, const char* file, int line,
247                   const std::string& msg) {
248  if (!condition) {
249    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
250                                        line, msg);
251  }
252}
253inline void Assert(bool condition, const char* file, int line) {
254  Assert(condition, file, line, "Assertion failed.");
255}
256
257// Verifies that condition is true; generates a non-fatal failure if
258// condition is false.
259inline void Expect(bool condition, const char* file, int line,
260                   const std::string& msg) {
261  if (!condition) {
262    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
263                                        file, line, msg);
264  }
265}
266inline void Expect(bool condition, const char* file, int line) {
267  Expect(condition, file, line, "Expectation failed.");
268}
269
270// Severity level of a log.
271enum LogSeverity { kInfo = 0, kWarning = 1 };
272
273// Valid values for the --gmock_verbose flag.
274
275// All logs (informational and warnings) are printed.
276const char kInfoVerbosity[] = "info";
277// Only warnings are printed.
278const char kWarningVerbosity[] = "warning";
279// No logs are printed.
280const char kErrorVerbosity[] = "error";
281
282// Returns true if and only if a log with the given severity is visible
283// according to the --gmock_verbose flag.
284GTEST_API_ bool LogIsVisible(LogSeverity severity);
285
286// Prints the given message to stdout if and only if 'severity' >= the level
287// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
288// 0, also prints the stack trace excluding the top
289// stack_frames_to_skip frames.  In opt mode, any positive
290// stack_frames_to_skip is treated as 0, since we don't know which
291// function calls will be inlined by the compiler and need to be
292// conservative.
293GTEST_API_ void Log(LogSeverity severity, const std::string& message,
294                    int stack_frames_to_skip);
295
296// A marker class that is used to resolve parameterless expectations to the
297// correct overload. This must not be instantiable, to prevent client code from
298// accidentally resolving to the overload; for example:
299//
300//    ON_CALL(mock, Method({}, nullptr))...
301//
302class WithoutMatchers {
303 private:
304  WithoutMatchers() {}
305  friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
306};
307
308// Internal use only: access the singleton instance of WithoutMatchers.
309GTEST_API_ WithoutMatchers GetWithoutMatchers();
310
311// Invalid<T>() is usable as an expression of type T, but will terminate
312// the program with an assertion failure if actually run.  This is useful
313// when a value of type T is needed for compilation, but the statement
314// will not really be executed (or we don't care if the statement
315// crashes).
316template <typename T>
317inline T Invalid() {
318  Assert(false, "", -1, "Internal error: attempt to return invalid value");
319#if defined(__GNUC__) || defined(__clang__)
320  __builtin_unreachable();
321#elif defined(_MSC_VER)
322  __assume(0);
323#else
324  return Invalid<T>();
325#endif
326}
327
328// Given a raw type (i.e. having no top-level reference or const
329// modifier) RawContainer that's either an STL-style container or a
330// native array, class StlContainerView<RawContainer> has the
331// following members:
332//
333//   - type is a type that provides an STL-style container view to
334//     (i.e. implements the STL container concept for) RawContainer;
335//   - const_reference is a type that provides a reference to a const
336//     RawContainer;
337//   - ConstReference(raw_container) returns a const reference to an STL-style
338//     container view to raw_container, which is a RawContainer.
339//   - Copy(raw_container) returns an STL-style container view of a
340//     copy of raw_container, which is a RawContainer.
341//
342// This generic version is used when RawContainer itself is already an
343// STL-style container.
344template <class RawContainer>
345class StlContainerView {
346 public:
347  typedef RawContainer type;
348  typedef const type& const_reference;
349
350  static const_reference ConstReference(const RawContainer& container) {
351    static_assert(!std::is_const<RawContainer>::value,
352                  "RawContainer type must not be const");
353    return container;
354  }
355  static type Copy(const RawContainer& container) { return container; }
356};
357
358// This specialization is used when RawContainer is a native array type.
359template <typename Element, size_t N>
360class StlContainerView<Element[N]> {
361 public:
362  typedef typename std::remove_const<Element>::type RawElement;
363  typedef internal::NativeArray<RawElement> type;
364  // NativeArray<T> can represent a native array either by value or by
365  // reference (selected by a constructor argument), so 'const type'
366  // can be used to reference a const native array.  We cannot
367  // 'typedef const type& const_reference' here, as that would mean
368  // ConstReference() has to return a reference to a local variable.
369  typedef const type const_reference;
370
371  static const_reference ConstReference(const Element (&array)[N]) {
372    static_assert(std::is_same<Element, RawElement>::value,
373                  "Element type must not be const");
374    return type(array, N, RelationToSourceReference());
375  }
376  static type Copy(const Element (&array)[N]) {
377    return type(array, N, RelationToSourceCopy());
378  }
379};
380
381// This specialization is used when RawContainer is a native array
382// represented as a (pointer, size) tuple.
383template <typename ElementPointer, typename Size>
384class StlContainerView< ::std::tuple<ElementPointer, Size> > {
385 public:
386  typedef typename std::remove_const<
387      typename std::pointer_traits<ElementPointer>::element_type>::type
388      RawElement;
389  typedef internal::NativeArray<RawElement> type;
390  typedef const type const_reference;
391
392  static const_reference ConstReference(
393      const ::std::tuple<ElementPointer, Size>& array) {
394    return type(std::get<0>(array), std::get<1>(array),
395                RelationToSourceReference());
396  }
397  static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
398    return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
399  }
400};
401
402// The following specialization prevents the user from instantiating
403// StlContainer with a reference type.
404template <typename T>
405class StlContainerView<T&>;
406
407// A type transform to remove constness from the first part of a pair.
408// Pairs like that are used as the value_type of associative containers,
409// and this transform produces a similar but assignable pair.
410template <typename T>
411struct RemoveConstFromKey {
412  typedef T type;
413};
414
415// Partially specialized to remove constness from std::pair<const K, V>.
416template <typename K, typename V>
417struct RemoveConstFromKey<std::pair<const K, V> > {
418  typedef std::pair<K, V> type;
419};
420
421// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
422// reduce code size.
423GTEST_API_ void IllegalDoDefault(const char* file, int line);
424
425template <typename F, typename Tuple, size_t... Idx>
426auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
427    -> decltype(std::forward<F>(f)(
428        std::get<Idx>(std::forward<Tuple>(args))...)) {
429  return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
430}
431
432// Apply the function to a tuple of arguments.
433template <typename F, typename Tuple>
434auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
435    std::forward<F>(f), std::forward<Tuple>(args),
436    MakeIndexSequence<std::tuple_size<
437        typename std::remove_reference<Tuple>::type>::value>())) {
438  return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
439                   MakeIndexSequence<std::tuple_size<
440                       typename std::remove_reference<Tuple>::type>::value>());
441}
442
443// Template struct Function<F>, where F must be a function type, contains
444// the following typedefs:
445//
446//   Result:               the function's return type.
447//   Arg<N>:               the type of the N-th argument, where N starts with 0.
448//   ArgumentTuple:        the tuple type consisting of all parameters of F.
449//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
450//                         parameters of F.
451//   MakeResultVoid:       the function type obtained by substituting void
452//                         for the return type of F.
453//   MakeResultIgnoredValue:
454//                         the function type obtained by substituting Something
455//                         for the return type of F.
456template <typename T>
457struct Function;
458
459template <typename R, typename... Args>
460struct Function<R(Args...)> {
461  using Result = R;
462  static constexpr size_t ArgumentCount = sizeof...(Args);
463  template <size_t I>
464  using Arg = ElemFromList<I, Args...>;
465  using ArgumentTuple = std::tuple<Args...>;
466  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
467  using MakeResultVoid = void(Args...);
468  using MakeResultIgnoredValue = IgnoredValue(Args...);
469};
470
471template <typename R, typename... Args>
472constexpr size_t Function<R(Args...)>::ArgumentCount;
473
474// Workaround for MSVC error C2039: 'type': is not a member of 'std'
475// when std::tuple_element is used.
476// See: https://github.com/google/googletest/issues/3931
477// Can be replaced with std::tuple_element_t in C++14.
478template <size_t I, typename T>
479using TupleElement = typename std::tuple_element<I, T>::type;
480
481bool Base64Unescape(const std::string& encoded, std::string* decoded);
482
483#ifdef _MSC_VER
484#pragma warning(pop)
485#endif
486
487}  // namespace internal
488}  // namespace testing
489
490#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
491