1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Google Mock - a framework for writing C++ mock classes.
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.
37 // GOOGLETEST_CM0002 DO NOT DELETE
39 // IWYU pragma: private, include "gmock/gmock.h"
41 #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
42 #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
45 #include <ostream> // NOLINT
47 #include <type_traits>
48 #include "gmock/internal/gmock-port.h"
49 #include "gtest/gtest.h"
58 // Silence MSVC C4100 (unreferenced formal parameter) and
59 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
61 # pragma warning(push)
62 # pragma warning(disable:4100)
63 # pragma warning(disable:4805)
66 // Joins a vector of strings as if they are fields of a tuple; returns
68 GTEST_API_
std::string
JoinAsTuple(const Strings
& fields
);
70 // Converts an identifier name to a space-separated list of lower-case
71 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
72 // treated as one word. For example, both "FooBar123" and
73 // "foo_bar_123" are converted to "foo bar 123".
74 GTEST_API_
std::string
ConvertIdentifierNameToWords(const char* id_name
);
76 // PointeeOf<Pointer>::type is the type of a value pointed to by a
77 // Pointer, which can be either a smart pointer or a raw pointer. The
78 // following default implementation is for the case where Pointer is a
80 template <typename Pointer
>
82 // Smart pointer classes define type element_type as the type of
84 typedef typename
Pointer::element_type type
;
86 // This specialization is for the raw pointer case.
88 struct PointeeOf
<T
*> { typedef T type
; }; // NOLINT
90 // GetRawPointer(p) returns the raw pointer underlying p when p is a
91 // smart pointer, or returns p itself when p is already a raw pointer.
92 // The following default implementation is for the smart pointer case.
93 template <typename Pointer
>
94 inline const typename
Pointer::element_type
* GetRawPointer(const Pointer
& p
) {
97 // This overloaded version is for the raw pointer case.
98 template <typename Element
>
99 inline Element
* GetRawPointer(Element
* p
) { return p
; }
101 // MSVC treats wchar_t as a native type usually, but treats it as the
102 // same as unsigned short when the compiler option /Zc:wchar_t- is
103 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
105 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
106 // wchar_t is a typedef.
108 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
111 // In what follows, we use the term "kind" to indicate whether a type
112 // is bool, an integer type (excluding bool), a floating-point type,
113 // or none of them. This categorization is useful for determining
114 // when a matcher argument type can be safely converted to another
115 // type in the implementation of SafeMatcherCast.
117 kBool
, kInteger
, kFloatingPoint
, kOther
120 // KindOf<T>::value is the kind of type T.
121 template <typename T
> struct KindOf
{
122 enum { value
= kOther
}; // The default kind.
125 // This macro declares that the kind of 'type' is 'kind'.
126 #define GMOCK_DECLARE_KIND_(type, kind) \
127 template <> struct KindOf<type> { enum { value = kind }; }
129 GMOCK_DECLARE_KIND_(bool, kBool
);
131 // All standard integer types.
132 GMOCK_DECLARE_KIND_(char, kInteger
);
133 GMOCK_DECLARE_KIND_(signed char, kInteger
);
134 GMOCK_DECLARE_KIND_(unsigned char, kInteger
);
135 GMOCK_DECLARE_KIND_(short, kInteger
); // NOLINT
136 GMOCK_DECLARE_KIND_(unsigned short, kInteger
); // NOLINT
137 GMOCK_DECLARE_KIND_(int, kInteger
);
138 GMOCK_DECLARE_KIND_(unsigned int, kInteger
);
139 GMOCK_DECLARE_KIND_(long, kInteger
); // NOLINT
140 GMOCK_DECLARE_KIND_(unsigned long, kInteger
); // NOLINT
142 #if GMOCK_WCHAR_T_IS_NATIVE_
143 GMOCK_DECLARE_KIND_(wchar_t, kInteger
);
146 // Non-standard integer types.
147 GMOCK_DECLARE_KIND_(Int64
, kInteger
);
148 GMOCK_DECLARE_KIND_(UInt64
, kInteger
);
150 // All standard floating-point types.
151 GMOCK_DECLARE_KIND_(float, kFloatingPoint
);
152 GMOCK_DECLARE_KIND_(double, kFloatingPoint
);
153 GMOCK_DECLARE_KIND_(long double, kFloatingPoint
);
155 #undef GMOCK_DECLARE_KIND_
157 // Evaluates to the kind of 'type'.
158 #define GMOCK_KIND_OF_(type) \
159 static_cast< ::testing::internal::TypeKind>( \
160 ::testing::internal::KindOf<type>::value)
162 // Evaluates to true if and only if integer type T is signed.
163 #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
165 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
166 // is true if and only if arithmetic type From can be losslessly converted to
167 // arithmetic type To.
169 // It's the user's responsibility to ensure that both From and To are
170 // raw (i.e. has no CV modifier, is not a pointer, and is not a
171 // reference) built-in arithmetic types, kFromKind is the kind of
172 // From, and kToKind is the kind of To; the value is
173 // implementation-defined when the above pre-condition is violated.
174 template <TypeKind kFromKind
, typename From
, TypeKind kToKind
, typename To
>
175 struct LosslessArithmeticConvertibleImpl
: public std::false_type
{};
177 // Converting bool to bool is lossless.
179 struct LosslessArithmeticConvertibleImpl
<kBool
, bool, kBool
, bool>
180 : public std::true_type
{};
182 // Converting bool to any integer type is lossless.
183 template <typename To
>
184 struct LosslessArithmeticConvertibleImpl
<kBool
, bool, kInteger
, To
>
185 : public std::true_type
{};
187 // Converting bool to any floating-point type is lossless.
188 template <typename To
>
189 struct LosslessArithmeticConvertibleImpl
<kBool
, bool, kFloatingPoint
, To
>
190 : public std::true_type
{};
192 // Converting an integer to bool is lossy.
193 template <typename From
>
194 struct LosslessArithmeticConvertibleImpl
<kInteger
, From
, kBool
, bool>
195 : public std::false_type
{};
197 // Converting an integer to another non-bool integer is lossless
198 // if and only if the target type's range encloses the source type's range.
199 template <typename From
, typename To
>
200 struct LosslessArithmeticConvertibleImpl
<kInteger
, From
, kInteger
, To
>
201 : public bool_constant
<
202 // When converting from a smaller size to a larger size, we are
203 // fine as long as we are not converting from signed to unsigned.
204 ((sizeof(From
) < sizeof(To
)) &&
205 (!GMOCK_IS_SIGNED_(From
) || GMOCK_IS_SIGNED_(To
))) ||
206 // When converting between the same size, the signedness must match.
207 ((sizeof(From
) == sizeof(To
)) &&
208 (GMOCK_IS_SIGNED_(From
) == GMOCK_IS_SIGNED_(To
)))> {}; // NOLINT
210 #undef GMOCK_IS_SIGNED_
212 // Converting an integer to a floating-point type may be lossy, since
213 // the format of a floating-point number is implementation-defined.
214 template <typename From
, typename To
>
215 struct LosslessArithmeticConvertibleImpl
<kInteger
, From
, kFloatingPoint
, To
>
216 : public std::false_type
{};
218 // Converting a floating-point to bool is lossy.
219 template <typename From
>
220 struct LosslessArithmeticConvertibleImpl
<kFloatingPoint
, From
, kBool
, bool>
221 : public std::false_type
{};
223 // Converting a floating-point to an integer is lossy.
224 template <typename From
, typename To
>
225 struct LosslessArithmeticConvertibleImpl
<kFloatingPoint
, From
, kInteger
, To
>
226 : public std::false_type
{};
228 // Converting a floating-point to another floating-point is lossless
229 // if and only if the target type is at least as big as the source type.
230 template <typename From
, typename To
>
231 struct LosslessArithmeticConvertibleImpl
<
232 kFloatingPoint
, From
, kFloatingPoint
, To
>
233 : public bool_constant
<sizeof(From
) <= sizeof(To
)> {}; // NOLINT
235 // LosslessArithmeticConvertible<From, To>::value is true if and only if
236 // arithmetic type From can be losslessly converted to arithmetic type To.
238 // It's the user's responsibility to ensure that both From and To are
239 // raw (i.e. has no CV modifier, is not a pointer, and is not a
240 // reference) built-in arithmetic types; the value is
241 // implementation-defined when the above pre-condition is violated.
242 template <typename From
, typename To
>
243 struct LosslessArithmeticConvertible
244 : public LosslessArithmeticConvertibleImpl
<
245 GMOCK_KIND_OF_(From
), From
, GMOCK_KIND_OF_(To
), To
> {}; // NOLINT
247 // This interface knows how to report a Google Mock failure (either
248 // non-fatal or fatal).
249 class FailureReporterInterface
{
251 // The type of a failure (either non-fatal or fatal).
256 virtual ~FailureReporterInterface() {}
258 // Reports a failure that occurred at the given source file location.
259 virtual void ReportFailure(FailureType type
, const char* file
, int line
,
260 const std::string
& message
) = 0;
263 // Returns the failure reporter used by Google Mock.
264 GTEST_API_ FailureReporterInterface
* GetFailureReporter();
266 // Asserts that condition is true; aborts the process with the given
267 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
268 // as Google Mock might be used to mock the log sink itself. We
269 // inline this function to prevent it from showing up in the stack
271 inline void Assert(bool condition
, const char* file
, int line
,
272 const std::string
& msg
) {
274 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal
,
278 inline void Assert(bool condition
, const char* file
, int line
) {
279 Assert(condition
, file
, line
, "Assertion failed.");
282 // Verifies that condition is true; generates a non-fatal failure if
283 // condition is false.
284 inline void Expect(bool condition
, const char* file
, int line
,
285 const std::string
& msg
) {
287 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal
,
291 inline void Expect(bool condition
, const char* file
, int line
) {
292 Expect(condition
, file
, line
, "Expectation failed.");
295 // Severity level of a log.
301 // Valid values for the --gmock_verbose flag.
303 // All logs (informational and warnings) are printed.
304 const char kInfoVerbosity
[] = "info";
305 // Only warnings are printed.
306 const char kWarningVerbosity
[] = "warning";
307 // No logs are printed.
308 const char kErrorVerbosity
[] = "error";
310 // Returns true if and only if a log with the given severity is visible
311 // according to the --gmock_verbose flag.
312 GTEST_API_
bool LogIsVisible(LogSeverity severity
);
314 // Prints the given message to stdout if and only if 'severity' >= the level
315 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
316 // 0, also prints the stack trace excluding the top
317 // stack_frames_to_skip frames. In opt mode, any positive
318 // stack_frames_to_skip is treated as 0, since we don't know which
319 // function calls will be inlined by the compiler and need to be
321 GTEST_API_
void Log(LogSeverity severity
, const std::string
& message
,
322 int stack_frames_to_skip
);
324 // A marker class that is used to resolve parameterless expectations to the
325 // correct overload. This must not be instantiable, to prevent client code from
326 // accidentally resolving to the overload; for example:
328 // ON_CALL(mock, Method({}, nullptr))...
330 class WithoutMatchers
{
333 friend GTEST_API_ WithoutMatchers
GetWithoutMatchers();
336 // Internal use only: access the singleton instance of WithoutMatchers.
337 GTEST_API_ WithoutMatchers
GetWithoutMatchers();
341 // Disable MSVC warnings for infinite recursion, since in this case the
342 // the recursion is unreachable.
344 # pragma warning(push)
345 # pragma warning(disable:4717)
348 // Invalid<T>() is usable as an expression of type T, but will terminate
349 // the program with an assertion failure if actually run. This is useful
350 // when a value of type T is needed for compilation, but the statement
351 // will not really be executed (or we don't care if the statement
353 template <typename T
>
355 Assert(false, "", -1, "Internal error: attempt to return invalid value");
356 // This statement is unreachable, and would never terminate even if it
357 // could be reached. It is provided only to placate compiler warnings
358 // about missing return statements.
363 # pragma warning(pop)
366 // Given a raw type (i.e. having no top-level reference or const
367 // modifier) RawContainer that's either an STL-style container or a
368 // native array, class StlContainerView<RawContainer> has the
369 // following members:
371 // - type is a type that provides an STL-style container view to
372 // (i.e. implements the STL container concept for) RawContainer;
373 // - const_reference is a type that provides a reference to a const
375 // - ConstReference(raw_container) returns a const reference to an STL-style
376 // container view to raw_container, which is a RawContainer.
377 // - Copy(raw_container) returns an STL-style container view of a
378 // copy of raw_container, which is a RawContainer.
380 // This generic version is used when RawContainer itself is already an
381 // STL-style container.
382 template <class RawContainer
>
383 class StlContainerView
{
385 typedef RawContainer type
;
386 typedef const type
& const_reference
;
388 static const_reference
ConstReference(const RawContainer
& container
) {
389 static_assert(!std::is_const
<RawContainer
>::value
,
390 "RawContainer type must not be const");
393 static type
Copy(const RawContainer
& container
) { return container
; }
396 // This specialization is used when RawContainer is a native array type.
397 template <typename Element
, size_t N
>
398 class StlContainerView
<Element
[N
]> {
400 typedef typename
std::remove_const
<Element
>::type RawElement
;
401 typedef internal::NativeArray
<RawElement
> type
;
402 // NativeArray<T> can represent a native array either by value or by
403 // reference (selected by a constructor argument), so 'const type'
404 // can be used to reference a const native array. We cannot
405 // 'typedef const type& const_reference' here, as that would mean
406 // ConstReference() has to return a reference to a local variable.
407 typedef const type const_reference
;
409 static const_reference
ConstReference(const Element (&array
)[N
]) {
410 static_assert(std::is_same
<Element
, RawElement
>::value
,
411 "Element type must not be const");
412 return type(array
, N
, RelationToSourceReference());
414 static type
Copy(const Element (&array
)[N
]) {
415 return type(array
, N
, RelationToSourceCopy());
419 // This specialization is used when RawContainer is a native array
420 // represented as a (pointer, size) tuple.
421 template <typename ElementPointer
, typename Size
>
422 class StlContainerView
< ::std::tuple
<ElementPointer
, Size
> > {
424 typedef typename
std::remove_const
<
425 typename
internal::PointeeOf
<ElementPointer
>::type
>::type RawElement
;
426 typedef internal::NativeArray
<RawElement
> type
;
427 typedef const type const_reference
;
429 static const_reference
ConstReference(
430 const ::std::tuple
<ElementPointer
, Size
>& array
) {
431 return type(std::get
<0>(array
), std::get
<1>(array
),
432 RelationToSourceReference());
434 static type
Copy(const ::std::tuple
<ElementPointer
, Size
>& array
) {
435 return type(std::get
<0>(array
), std::get
<1>(array
), RelationToSourceCopy());
439 // The following specialization prevents the user from instantiating
440 // StlContainer with a reference type.
441 template <typename T
> class StlContainerView
<T
&>;
443 // A type transform to remove constness from the first part of a pair.
444 // Pairs like that are used as the value_type of associative containers,
445 // and this transform produces a similar but assignable pair.
446 template <typename T
>
447 struct RemoveConstFromKey
{
451 // Partially specialized to remove constness from std::pair<const K, V>.
452 template <typename K
, typename V
>
453 struct RemoveConstFromKey
<std::pair
<const K
, V
> > {
454 typedef std::pair
<K
, V
> type
;
457 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
459 GTEST_API_
void IllegalDoDefault(const char* file
, int line
);
461 template <typename F
, typename Tuple
, size_t... Idx
>
462 auto ApplyImpl(F
&& f
, Tuple
&& args
, IndexSequence
<Idx
...>) -> decltype(
463 std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...)) {
464 return std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...);
467 // Apply the function to a tuple of arguments.
468 template <typename F
, typename Tuple
>
469 auto Apply(F
&& f
, Tuple
&& args
)
470 -> decltype(ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
471 MakeIndexSequence
<std::tuple_size
<Tuple
>::value
>())) {
472 return ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
473 MakeIndexSequence
<std::tuple_size
<Tuple
>::value
>());
476 // Template struct Function<F>, where F must be a function type, contains
477 // the following typedefs:
479 // Result: the function's return type.
480 // Arg<N>: the type of the N-th argument, where N starts with 0.
481 // ArgumentTuple: the tuple type consisting of all parameters of F.
482 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
484 // MakeResultVoid: the function type obtained by substituting void
485 // for the return type of F.
486 // MakeResultIgnoredValue:
487 // the function type obtained by substituting Something
488 // for the return type of F.
489 template <typename T
>
492 template <typename R
, typename
... Args
>
493 struct Function
<R(Args
...)> {
495 static constexpr size_t ArgumentCount
= sizeof...(Args
);
497 using Arg
= ElemFromList
<I
, typename MakeIndexSequence
<sizeof...(Args
)>::type
,
499 using ArgumentTuple
= std::tuple
<Args
...>;
500 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
501 using MakeResultVoid
= void(Args
...);
502 using MakeResultIgnoredValue
= IgnoredValue(Args
...);
505 template <typename R
, typename
... Args
>
506 constexpr size_t Function
<R(Args
...)>::ArgumentCount
;
509 # pragma warning(pop)
512 } // namespace internal
513 } // namespace testing
515 #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_