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 #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40 #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
43 #include <ostream> // NOLINT
45 #include <type_traits>
46 #include "gmock/internal/gmock-port.h"
47 #include "gtest/gtest.h"
56 // Silence MSVC C4100 (unreferenced formal parameter) and
57 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
59 # pragma warning(push)
60 # pragma warning(disable:4100)
61 # pragma warning(disable:4805)
64 // Joins a vector of strings as if they are fields of a tuple; returns
66 GTEST_API_
std::string
JoinAsTuple(const Strings
& fields
);
68 // Converts an identifier name to a space-separated list of lower-case
69 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
70 // treated as one word. For example, both "FooBar123" and
71 // "foo_bar_123" are converted to "foo bar 123".
72 GTEST_API_
std::string
ConvertIdentifierNameToWords(const char* id_name
);
74 // PointeeOf<Pointer>::type is the type of a value pointed to by a
75 // Pointer, which can be either a smart pointer or a raw pointer. The
76 // following default implementation is for the case where Pointer is a
78 template <typename Pointer
>
80 // Smart pointer classes define type element_type as the type of
82 typedef typename
Pointer::element_type type
;
84 // This specialization is for the raw pointer case.
86 struct PointeeOf
<T
*> { typedef T type
; }; // NOLINT
88 // GetRawPointer(p) returns the raw pointer underlying p when p is a
89 // smart pointer, or returns p itself when p is already a raw pointer.
90 // The following default implementation is for the smart pointer case.
91 template <typename Pointer
>
92 inline const typename
Pointer::element_type
* GetRawPointer(const Pointer
& p
) {
95 // This overloaded version is for the raw pointer case.
96 template <typename Element
>
97 inline Element
* GetRawPointer(Element
* p
) { return p
; }
99 // MSVC treats wchar_t as a native type usually, but treats it as the
100 // same as unsigned short when the compiler option /Zc:wchar_t- is
101 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
103 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
104 // wchar_t is a typedef.
106 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
109 // In what follows, we use the term "kind" to indicate whether a type
110 // is bool, an integer type (excluding bool), a floating-point type,
111 // or none of them. This categorization is useful for determining
112 // when a matcher argument type can be safely converted to another
113 // type in the implementation of SafeMatcherCast.
115 kBool
, kInteger
, kFloatingPoint
, kOther
118 // KindOf<T>::value is the kind of type T.
119 template <typename T
> struct KindOf
{
120 enum { value
= kOther
}; // The default kind.
123 // This macro declares that the kind of 'type' is 'kind'.
124 #define GMOCK_DECLARE_KIND_(type, kind) \
125 template <> struct KindOf<type> { enum { value = kind }; }
127 GMOCK_DECLARE_KIND_(bool, kBool
);
129 // All standard integer types.
130 GMOCK_DECLARE_KIND_(char, kInteger
);
131 GMOCK_DECLARE_KIND_(signed char, kInteger
);
132 GMOCK_DECLARE_KIND_(unsigned char, kInteger
);
133 GMOCK_DECLARE_KIND_(short, kInteger
); // NOLINT
134 GMOCK_DECLARE_KIND_(unsigned short, kInteger
); // NOLINT
135 GMOCK_DECLARE_KIND_(int, kInteger
);
136 GMOCK_DECLARE_KIND_(unsigned int, kInteger
);
137 GMOCK_DECLARE_KIND_(long, kInteger
); // NOLINT
138 GMOCK_DECLARE_KIND_(unsigned long, kInteger
); // NOLINT
139 GMOCK_DECLARE_KIND_(long long, kInteger
); // NOLINT
140 GMOCK_DECLARE_KIND_(unsigned long long, kInteger
); // NOLINT
142 #if GMOCK_WCHAR_T_IS_NATIVE_
143 GMOCK_DECLARE_KIND_(wchar_t, kInteger
);
146 // All standard floating-point types.
147 GMOCK_DECLARE_KIND_(float, kFloatingPoint
);
148 GMOCK_DECLARE_KIND_(double, kFloatingPoint
);
149 GMOCK_DECLARE_KIND_(long double, kFloatingPoint
);
151 #undef GMOCK_DECLARE_KIND_
153 // Evaluates to the kind of 'type'.
154 #define GMOCK_KIND_OF_(type) \
155 static_cast< ::testing::internal::TypeKind>( \
156 ::testing::internal::KindOf<type>::value)
158 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
159 // is true if and only if arithmetic type From can be losslessly converted to
160 // arithmetic type To.
162 // It's the user's responsibility to ensure that both From and To are
163 // raw (i.e. has no CV modifier, is not a pointer, and is not a
164 // reference) built-in arithmetic types, kFromKind is the kind of
165 // From, and kToKind is the kind of To; the value is
166 // implementation-defined when the above pre-condition is violated.
167 template <TypeKind kFromKind
, typename From
, TypeKind kToKind
, typename To
>
168 using LosslessArithmeticConvertibleImpl
= std::integral_constant
<
171 // Converting from bool is always lossless
172 (kFromKind
== kBool
) ? true
173 // Converting between any other type kinds will be lossy if the type
174 // kinds are not the same.
175 : (kFromKind
!= kToKind
) ? false
176 : (kFromKind
== kInteger
&&
177 // Converting between integers of different widths is allowed so long
178 // as the conversion does not go from signed to unsigned.
179 (((sizeof(From
) < sizeof(To
)) &&
180 !(std::is_signed
<From
>::value
&& !std::is_signed
<To
>::value
)) ||
181 // Converting between integers of the same width only requires the
182 // two types to have the same signedness.
183 ((sizeof(From
) == sizeof(To
)) &&
184 (std::is_signed
<From
>::value
== std::is_signed
<To
>::value
)))
186 // Floating point conversions are lossless if and only if `To` is at least
187 // as wide as `From`.
188 : (kFromKind
== kFloatingPoint
&& (sizeof(From
) <= sizeof(To
))) ? true
193 // LosslessArithmeticConvertible<From, To>::value is true if and only if
194 // arithmetic type From can be losslessly converted to arithmetic type To.
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; the value is
199 // implementation-defined when the above pre-condition is violated.
200 template <typename From
, typename To
>
201 using LosslessArithmeticConvertible
=
202 LosslessArithmeticConvertibleImpl
<GMOCK_KIND_OF_(From
), From
,
203 GMOCK_KIND_OF_(To
), To
>;
205 // This interface knows how to report a Google Mock failure (either
206 // non-fatal or fatal).
207 class FailureReporterInterface
{
209 // The type of a failure (either non-fatal or fatal).
214 virtual ~FailureReporterInterface() {}
216 // Reports a failure that occurred at the given source file location.
217 virtual void ReportFailure(FailureType type
, const char* file
, int line
,
218 const std::string
& message
) = 0;
221 // Returns the failure reporter used by Google Mock.
222 GTEST_API_ FailureReporterInterface
* GetFailureReporter();
224 // Asserts that condition is true; aborts the process with the given
225 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
226 // as Google Mock might be used to mock the log sink itself. We
227 // inline this function to prevent it from showing up in the stack
229 inline void Assert(bool condition
, const char* file
, int line
,
230 const std::string
& msg
) {
232 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal
,
236 inline void Assert(bool condition
, const char* file
, int line
) {
237 Assert(condition
, file
, line
, "Assertion failed.");
240 // Verifies that condition is true; generates a non-fatal failure if
241 // condition is false.
242 inline void Expect(bool condition
, const char* file
, int line
,
243 const std::string
& msg
) {
245 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal
,
249 inline void Expect(bool condition
, const char* file
, int line
) {
250 Expect(condition
, file
, line
, "Expectation failed.");
253 // Severity level of a log.
259 // Valid values for the --gmock_verbose flag.
261 // All logs (informational and warnings) are printed.
262 const char kInfoVerbosity
[] = "info";
263 // Only warnings are printed.
264 const char kWarningVerbosity
[] = "warning";
265 // No logs are printed.
266 const char kErrorVerbosity
[] = "error";
268 // Returns true if and only if a log with the given severity is visible
269 // according to the --gmock_verbose flag.
270 GTEST_API_
bool LogIsVisible(LogSeverity severity
);
272 // Prints the given message to stdout if and only if 'severity' >= the level
273 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
274 // 0, also prints the stack trace excluding the top
275 // stack_frames_to_skip frames. In opt mode, any positive
276 // stack_frames_to_skip is treated as 0, since we don't know which
277 // function calls will be inlined by the compiler and need to be
279 GTEST_API_
void Log(LogSeverity severity
, const std::string
& message
,
280 int stack_frames_to_skip
);
282 // A marker class that is used to resolve parameterless expectations to the
283 // correct overload. This must not be instantiable, to prevent client code from
284 // accidentally resolving to the overload; for example:
286 // ON_CALL(mock, Method({}, nullptr))...
288 class WithoutMatchers
{
291 friend GTEST_API_ WithoutMatchers
GetWithoutMatchers();
294 // Internal use only: access the singleton instance of WithoutMatchers.
295 GTEST_API_ WithoutMatchers
GetWithoutMatchers();
297 // Disable MSVC warnings for infinite recursion, since in this case the
298 // the recursion is unreachable.
300 # pragma warning(push)
301 # pragma warning(disable:4717)
304 // Invalid<T>() is usable as an expression of type T, but will terminate
305 // the program with an assertion failure if actually run. This is useful
306 // when a value of type T is needed for compilation, but the statement
307 // will not really be executed (or we don't care if the statement
309 template <typename T
>
311 Assert(false, "", -1, "Internal error: attempt to return invalid value");
312 // This statement is unreachable, and would never terminate even if it
313 // could be reached. It is provided only to placate compiler warnings
314 // about missing return statements.
319 # pragma warning(pop)
322 // Given a raw type (i.e. having no top-level reference or const
323 // modifier) RawContainer that's either an STL-style container or a
324 // native array, class StlContainerView<RawContainer> has the
325 // following members:
327 // - type is a type that provides an STL-style container view to
328 // (i.e. implements the STL container concept for) RawContainer;
329 // - const_reference is a type that provides a reference to a const
331 // - ConstReference(raw_container) returns a const reference to an STL-style
332 // container view to raw_container, which is a RawContainer.
333 // - Copy(raw_container) returns an STL-style container view of a
334 // copy of raw_container, which is a RawContainer.
336 // This generic version is used when RawContainer itself is already an
337 // STL-style container.
338 template <class RawContainer
>
339 class StlContainerView
{
341 typedef RawContainer type
;
342 typedef const type
& const_reference
;
344 static const_reference
ConstReference(const RawContainer
& container
) {
345 static_assert(!std::is_const
<RawContainer
>::value
,
346 "RawContainer type must not be const");
349 static type
Copy(const RawContainer
& container
) { return container
; }
352 // This specialization is used when RawContainer is a native array type.
353 template <typename Element
, size_t N
>
354 class StlContainerView
<Element
[N
]> {
356 typedef typename
std::remove_const
<Element
>::type RawElement
;
357 typedef internal::NativeArray
<RawElement
> type
;
358 // NativeArray<T> can represent a native array either by value or by
359 // reference (selected by a constructor argument), so 'const type'
360 // can be used to reference a const native array. We cannot
361 // 'typedef const type& const_reference' here, as that would mean
362 // ConstReference() has to return a reference to a local variable.
363 typedef const type const_reference
;
365 static const_reference
ConstReference(const Element (&array
)[N
]) {
366 static_assert(std::is_same
<Element
, RawElement
>::value
,
367 "Element type must not be const");
368 return type(array
, N
, RelationToSourceReference());
370 static type
Copy(const Element (&array
)[N
]) {
371 return type(array
, N
, RelationToSourceCopy());
375 // This specialization is used when RawContainer is a native array
376 // represented as a (pointer, size) tuple.
377 template <typename ElementPointer
, typename Size
>
378 class StlContainerView
< ::std::tuple
<ElementPointer
, Size
> > {
380 typedef typename
std::remove_const
<
381 typename
internal::PointeeOf
<ElementPointer
>::type
>::type RawElement
;
382 typedef internal::NativeArray
<RawElement
> type
;
383 typedef const type const_reference
;
385 static const_reference
ConstReference(
386 const ::std::tuple
<ElementPointer
, Size
>& array
) {
387 return type(std::get
<0>(array
), std::get
<1>(array
),
388 RelationToSourceReference());
390 static type
Copy(const ::std::tuple
<ElementPointer
, Size
>& array
) {
391 return type(std::get
<0>(array
), std::get
<1>(array
), RelationToSourceCopy());
395 // The following specialization prevents the user from instantiating
396 // StlContainer with a reference type.
397 template <typename T
> class StlContainerView
<T
&>;
399 // A type transform to remove constness from the first part of a pair.
400 // Pairs like that are used as the value_type of associative containers,
401 // and this transform produces a similar but assignable pair.
402 template <typename T
>
403 struct RemoveConstFromKey
{
407 // Partially specialized to remove constness from std::pair<const K, V>.
408 template <typename K
, typename V
>
409 struct RemoveConstFromKey
<std::pair
<const K
, V
> > {
410 typedef std::pair
<K
, V
> type
;
413 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
415 GTEST_API_
void IllegalDoDefault(const char* file
, int line
);
417 template <typename F
, typename Tuple
, size_t... Idx
>
418 auto ApplyImpl(F
&& f
, Tuple
&& args
, IndexSequence
<Idx
...>) -> decltype(
419 std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...)) {
420 return std::forward
<F
>(f
)(std::get
<Idx
>(std::forward
<Tuple
>(args
))...);
423 // Apply the function to a tuple of arguments.
424 template <typename F
, typename Tuple
>
425 auto Apply(F
&& f
, Tuple
&& args
)
426 -> decltype(ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
427 MakeIndexSequence
<std::tuple_size
<Tuple
>::value
>())) {
428 return ApplyImpl(std::forward
<F
>(f
), std::forward
<Tuple
>(args
),
429 MakeIndexSequence
<std::tuple_size
<Tuple
>::value
>());
432 // Template struct Function<F>, where F must be a function type, contains
433 // the following typedefs:
435 // Result: the function's return type.
436 // Arg<N>: the type of the N-th argument, where N starts with 0.
437 // ArgumentTuple: the tuple type consisting of all parameters of F.
438 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
440 // MakeResultVoid: the function type obtained by substituting void
441 // for the return type of F.
442 // MakeResultIgnoredValue:
443 // the function type obtained by substituting Something
444 // for the return type of F.
445 template <typename T
>
448 template <typename R
, typename
... Args
>
449 struct Function
<R(Args
...)> {
451 static constexpr size_t ArgumentCount
= sizeof...(Args
);
453 using Arg
= ElemFromList
<I
, Args
...>;
454 using ArgumentTuple
= std::tuple
<Args
...>;
455 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
456 using MakeResultVoid
= void(Args
...);
457 using MakeResultIgnoredValue
= IgnoredValue(Args
...);
460 template <typename R
, typename
... Args
>
461 constexpr size_t Function
<R(Args
...)>::ArgumentCount
;
464 # pragma warning(pop)
467 } // namespace internal
468 } // namespace testing
470 #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_