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 "gmock/internal/gmock-generated-internal-utils.h"
46 #include "gmock/internal/gmock-port.h"
47 #include "gtest/gtest.h"
52 // Silence MSVC C4100 (unreferenced formal parameter) and
53 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
55 # pragma warning(push)
56 # pragma warning(disable:4100)
57 # pragma warning(disable:4805)
60 // Joins a vector of strings as if they are fields of a tuple; returns
62 GTEST_API_ std::string JoinAsTuple(const Strings& fields);
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".
68 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
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
74 template <typename Pointer>
76 // Smart pointer classes define type element_type as the type of
78 typedef typename Pointer::element_type type;
80 // This specialization is for the raw pointer case.
82 struct PointeeOf<T*> { typedef T type; }; // NOLINT
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.
87 template <typename Pointer>
88 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
91 // This overloaded version is for the raw pointer case.
92 template <typename Element>
93 inline Element* GetRawPointer(Element* p) { return p; }
95 // This comparator allows linked_ptr to be stored in sets.
97 struct 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();
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.
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
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.
116 # define GMOCK_WCHAR_T_IS_NATIVE_ 1
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.
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
127 // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
129 #if !defined(__WCHAR_UNSIGNED__)
130 // signed/unsigned wchar_t are valid types.
131 # define GMOCK_HAS_SIGNED_WCHAR_T_ 1
135 // In what follows, we use the term "kind" to indicate whether a type
136 // is bool, an integer type (excluding bool), a floating-point type,
137 // or none of them. This categorization is useful for determining
138 // when a matcher argument type can be safely converted to another
139 // type in the implementation of SafeMatcherCast.
141 kBool, kInteger, kFloatingPoint, kOther
144 // KindOf<T>::value is the kind of type T.
145 template <typename T> struct KindOf {
146 enum { value = kOther }; // The default kind.
149 // This macro declares that the kind of 'type' is 'kind'.
150 #define GMOCK_DECLARE_KIND_(type, kind) \
151 template <> struct KindOf<type> { enum { value = kind }; }
153 GMOCK_DECLARE_KIND_(bool, kBool);
155 // All standard integer types.
156 GMOCK_DECLARE_KIND_(char, kInteger);
157 GMOCK_DECLARE_KIND_(signed char, kInteger);
158 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
159 GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
160 GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
161 GMOCK_DECLARE_KIND_(int, kInteger);
162 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
163 GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
164 GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
166 #if GMOCK_WCHAR_T_IS_NATIVE_
167 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
170 // Non-standard integer types.
171 GMOCK_DECLARE_KIND_(Int64, kInteger);
172 GMOCK_DECLARE_KIND_(UInt64, kInteger);
174 // All standard floating-point types.
175 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
176 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
177 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
179 #undef GMOCK_DECLARE_KIND_
181 // Evaluates to the kind of 'type'.
182 #define GMOCK_KIND_OF_(type) \
183 static_cast< ::testing::internal::TypeKind>( \
184 ::testing::internal::KindOf<type>::value)
186 // Evaluates to true iff integer type T is signed.
187 #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
189 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
190 // is true iff arithmetic type From can be losslessly converted to
191 // arithmetic type To.
193 // It's the user's responsibility to ensure that both From and To are
194 // raw (i.e. has no CV modifier, is not a pointer, and is not a
195 // reference) built-in arithmetic types, kFromKind is the kind of
196 // From, and kToKind is the kind of To; the value is
197 // implementation-defined when the above pre-condition is violated.
198 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
199 struct LosslessArithmeticConvertibleImpl : public false_type {};
201 // Converting bool to bool is lossless.
203 struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
204 : public true_type {}; // NOLINT
206 // Converting bool to any integer type is lossless.
207 template <typename To>
208 struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
209 : public true_type {}; // NOLINT
211 // Converting bool to any floating-point type is lossless.
212 template <typename To>
213 struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
214 : public true_type {}; // NOLINT
216 // Converting an integer to bool is lossy.
217 template <typename From>
218 struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
219 : public false_type {}; // NOLINT
221 // Converting an integer to another non-bool integer is lossless iff
222 // the target type's range encloses the source type's range.
223 template <typename From, typename To>
224 struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
225 : public bool_constant<
226 // When converting from a smaller size to a larger size, we are
227 // fine as long as we are not converting from signed to unsigned.
228 ((sizeof(From) < sizeof(To)) &&
229 (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
230 // When converting between the same size, the signedness must match.
231 ((sizeof(From) == sizeof(To)) &&
232 (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
234 #undef GMOCK_IS_SIGNED_
236 // Converting an integer to a floating-point type may be lossy, since
237 // the format of a floating-point number is implementation-defined.
238 template <typename From, typename To>
239 struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
240 : public false_type {}; // NOLINT
242 // Converting a floating-point to bool is lossy.
243 template <typename From>
244 struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
245 : public false_type {}; // NOLINT
247 // Converting a floating-point to an integer is lossy.
248 template <typename From, typename To>
249 struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
250 : public false_type {}; // NOLINT
252 // Converting a floating-point to another floating-point is lossless
253 // iff the target type is at least as big as the source type.
254 template <typename From, typename To>
255 struct LosslessArithmeticConvertibleImpl<
256 kFloatingPoint, From, kFloatingPoint, To>
257 : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
259 // LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
260 // type From can be losslessly converted to arithmetic type To.
262 // It's the user's responsibility to ensure that both From and To are
263 // raw (i.e. has no CV modifier, is not a pointer, and is not a
264 // reference) built-in arithmetic types; the value is
265 // implementation-defined when the above pre-condition is violated.
266 template <typename From, typename To>
267 struct LosslessArithmeticConvertible
268 : public LosslessArithmeticConvertibleImpl<
269 GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
271 // This interface knows how to report a Google Mock failure (either
272 // non-fatal or fatal).
273 class FailureReporterInterface {
275 // The type of a failure (either non-fatal or fatal).
280 virtual ~FailureReporterInterface() {}
282 // Reports a failure that occurred at the given source file location.
283 virtual void ReportFailure(FailureType type, const char* file, int line,
284 const std::string& message) = 0;
287 // Returns the failure reporter used by Google Mock.
288 GTEST_API_ FailureReporterInterface* GetFailureReporter();
290 // Asserts that condition is true; aborts the process with the given
291 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
292 // as Google Mock might be used to mock the log sink itself. We
293 // inline this function to prevent it from showing up in the stack
295 inline void Assert(bool condition, const char* file, int line,
296 const std::string& msg) {
298 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
302 inline void Assert(bool condition, const char* file, int line) {
303 Assert(condition, file, line, "Assertion failed.");
306 // Verifies that condition is true; generates a non-fatal failure if
307 // condition is false.
308 inline void Expect(bool condition, const char* file, int line,
309 const std::string& msg) {
311 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
315 inline void Expect(bool condition, const char* file, int line) {
316 Expect(condition, file, line, "Expectation failed.");
319 // Severity level of a log.
325 // Valid values for the --gmock_verbose flag.
327 // All logs (informational and warnings) are printed.
328 const char kInfoVerbosity[] = "info";
329 // Only warnings are printed.
330 const char kWarningVerbosity[] = "warning";
331 // No logs are printed.
332 const char kErrorVerbosity[] = "error";
334 // Returns true iff a log with the given severity is visible according
335 // to the --gmock_verbose flag.
336 GTEST_API_ bool LogIsVisible(LogSeverity severity);
338 // Prints the given message to stdout iff 'severity' >= the level
339 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
340 // 0, also prints the stack trace excluding the top
341 // stack_frames_to_skip frames. In opt mode, any positive
342 // stack_frames_to_skip is treated as 0, since we don't know which
343 // function calls will be inlined by the compiler and need to be
345 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
346 int stack_frames_to_skip);
348 // A marker class that is used to resolve parameterless expectations to the
349 // correct overload. This must not be instantiable, to prevent client code from
350 // accidentally resolving to the overload; for example:
352 // ON_CALL(mock, Method({}, nullptr))...
354 class WithoutMatchers {
357 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
360 // Internal use only: access the singleton instance of WithoutMatchers.
361 GTEST_API_ WithoutMatchers GetWithoutMatchers();
363 // FIXME: group all type utilities together.
367 // is_reference<T>::value is non-zero iff T is a reference type.
368 template <typename T> struct is_reference : public false_type {};
369 template <typename T> struct is_reference<T&> : public true_type {};
371 // type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
372 template <typename T1, typename T2> struct type_equals : public false_type {};
373 template <typename T> struct type_equals<T, T> : public true_type {};
375 // remove_reference<T>::type removes the reference from type T, if any.
376 template <typename T> struct remove_reference { typedef T type; }; // NOLINT
377 template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
379 // DecayArray<T>::type turns an array type U[N] to const U* and preserves
380 // other types. Useful for saving a copy of a function argument.
381 template <typename T> struct DecayArray { typedef T type; }; // NOLINT
382 template <typename T, size_t N> struct DecayArray<T[N]> {
383 typedef const T* type;
385 // Sometimes people use arrays whose size is not available at the use site
386 // (e.g. extern const char kNamePrefix[]). This specialization covers that
388 template <typename T> struct DecayArray<T[]> {
389 typedef const T* type;
392 // Disable MSVC warnings for infinite recursion, since in this case the
393 // the recursion is unreachable.
395 # pragma warning(push)
396 # pragma warning(disable:4717)
399 // Invalid<T>() is usable as an expression of type T, but will terminate
400 // the program with an assertion failure if actually run. This is useful
401 // when a value of type T is needed for compilation, but the statement
402 // will not really be executed (or we don't care if the statement
404 template <typename T>
406 Assert(false, "", -1, "Internal error: attempt to return invalid value");
407 // This statement is unreachable, and would never terminate even if it
408 // could be reached. It is provided only to placate compiler warnings
409 // about missing return statements.
414 # pragma warning(pop)
417 // Given a raw type (i.e. having no top-level reference or const
418 // modifier) RawContainer that's either an STL-style container or a
419 // native array, class StlContainerView<RawContainer> has the
420 // following members:
422 // - type is a type that provides an STL-style container view to
423 // (i.e. implements the STL container concept for) RawContainer;
424 // - const_reference is a type that provides a reference to a const
426 // - ConstReference(raw_container) returns a const reference to an STL-style
427 // container view to raw_container, which is a RawContainer.
428 // - Copy(raw_container) returns an STL-style container view of a
429 // copy of raw_container, which is a RawContainer.
431 // This generic version is used when RawContainer itself is already an
432 // STL-style container.
433 template <class RawContainer>
434 class StlContainerView {
436 typedef RawContainer type;
437 typedef const type& const_reference;
439 static const_reference ConstReference(const RawContainer& container) {
440 // Ensures that RawContainer is not a const type.
441 testing::StaticAssertTypeEq<RawContainer,
442 GTEST_REMOVE_CONST_(RawContainer)>();
445 static type Copy(const RawContainer& container) { return container; }
448 // This specialization is used when RawContainer is a native array type.
449 template <typename Element, size_t N>
450 class StlContainerView<Element[N]> {
452 typedef GTEST_REMOVE_CONST_(Element) RawElement;
453 typedef internal::NativeArray<RawElement> type;
454 // NativeArray<T> can represent a native array either by value or by
455 // reference (selected by a constructor argument), so 'const type'
456 // can be used to reference a const native array. We cannot
457 // 'typedef const type& const_reference' here, as that would mean
458 // ConstReference() has to return a reference to a local variable.
459 typedef const type const_reference;
461 static const_reference ConstReference(const Element (&array)[N]) {
462 // Ensures that Element is not a const type.
463 testing::StaticAssertTypeEq<Element, RawElement>();
465 // The Nokia Symbian compiler confuses itself in template instantiation
466 // for this call without the cast to Element*:
467 // function call '[testing::internal::NativeArray<char *>].NativeArray(
468 // {lval} const char *[4], long, testing::internal::RelationToSource)'
470 // 'testing::internal::NativeArray<char *>::NativeArray(
471 // char *const *, unsigned int, testing::internal::RelationToSource)'
472 // (instantiating: 'testing::internal::ContainsMatcherImpl
473 // <const char * (&)[4]>::Matches(const char * (&)[4]) const')
474 // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
475 // ConstReference(const char * (&)[4])')
476 // (and though the N parameter type is mismatched in the above explicit
477 // conversion of it doesn't help - only the conversion of the array).
478 return type(const_cast<Element*>(&array[0]), N,
479 RelationToSourceReference());
481 return type(array, N, RelationToSourceReference());
482 #endif // GTEST_OS_SYMBIAN
484 static type Copy(const Element (&array)[N]) {
486 return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
488 return type(array, N, RelationToSourceCopy());
489 #endif // GTEST_OS_SYMBIAN
493 // This specialization is used when RawContainer is a native array
494 // represented as a (pointer, size) tuple.
495 template <typename ElementPointer, typename Size>
496 class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
498 typedef GTEST_REMOVE_CONST_(
499 typename internal::PointeeOf<ElementPointer>::type) RawElement;
500 typedef internal::NativeArray<RawElement> type;
501 typedef const type const_reference;
503 static const_reference ConstReference(
504 const ::testing::tuple<ElementPointer, Size>& array) {
505 return type(get<0>(array), get<1>(array), RelationToSourceReference());
507 static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
508 return type(get<0>(array), get<1>(array), RelationToSourceCopy());
512 // The following specialization prevents the user from instantiating
513 // StlContainer with a reference type.
514 template <typename T> class StlContainerView<T&>;
516 // A type transform to remove constness from the first part of a pair.
517 // Pairs like that are used as the value_type of associative containers,
518 // and this transform produces a similar but assignable pair.
519 template <typename T>
520 struct RemoveConstFromKey {
524 // Partially specialized to remove constness from std::pair<const K, V>.
525 template <typename K, typename V>
526 struct RemoveConstFromKey<std::pair<const K, V> > {
527 typedef std::pair<K, V> type;
530 // Mapping from booleans to types. Similar to boost::bool_<kValue> and
531 // std::integral_constant<bool, kValue>.
532 template <bool kValue>
533 struct BooleanConstant {};
535 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
537 GTEST_API_ void IllegalDoDefault(const char* file, int line);
540 // Helper types for Apply() below.
541 template <size_t... Is> struct int_pack { typedef int_pack type; };
543 template <class Pack, size_t I> struct append;
544 template <size_t... Is, size_t I>
545 struct append<int_pack<Is...>, I> : int_pack<Is..., I> {};
548 struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {};
549 template <> struct make_int_pack<0> : int_pack<> {};
551 template <typename F, typename Tuple, size_t... Idx>
552 auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
553 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
554 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
557 // Apply the function to a tuple of arguments.
558 template <typename F, typename Tuple>
559 auto Apply(F&& f, Tuple&& args)
560 -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
561 make_int_pack<std::tuple_size<Tuple>::value>())) {
562 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
563 make_int_pack<std::tuple_size<Tuple>::value>());
569 # pragma warning(pop)
572 } // namespace internal
573 } // namespace testing
575 #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_