gmock-internal-utils.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. // Author: wan@google.com (Zhanyong Wan)
  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. #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
  37. #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
  38. #include <stdio.h>
  39. #include <ostream> // NOLINT
  40. #include <string>
  41. #include "gmock/internal/gmock-generated-internal-utils.h"
  42. #include "gmock/internal/gmock-port.h"
  43. #include "gtest/gtest.h"
  44. namespace testing {
  45. namespace internal {
  46. // Converts an identifier name to a space-separated list of lower-case
  47. // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
  48. // treated as one word. For example, both "FooBar123" and
  49. // "foo_bar_123" are converted to "foo bar 123".
  50. GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name);
  51. // PointeeOf<Pointer>::type is the type of a value pointed to by a
  52. // Pointer, which can be either a smart pointer or a raw pointer. The
  53. // following default implementation is for the case where Pointer is a
  54. // smart pointer.
  55. template <typename Pointer>
  56. struct PointeeOf {
  57. // Smart pointer classes define type element_type as the type of
  58. // their pointees.
  59. typedef typename Pointer::element_type type;
  60. };
  61. // This specialization is for the raw pointer case.
  62. template <typename T>
  63. struct PointeeOf<T*> { typedef T type; }; // NOLINT
  64. // GetRawPointer(p) returns the raw pointer underlying p when p is a
  65. // smart pointer, or returns p itself when p is already a raw pointer.
  66. // The following default implementation is for the smart pointer case.
  67. template <typename Pointer>
  68. inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
  69. return p.get();
  70. }
  71. // This overloaded version is for the raw pointer case.
  72. template <typename Element>
  73. inline Element* GetRawPointer(Element* p) { return p; }
  74. // This comparator allows linked_ptr to be stored in sets.
  75. template <typename T>
  76. struct LinkedPtrLessThan {
  77. bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
  78. const ::testing::internal::linked_ptr<T>& rhs) const {
  79. return lhs.get() < rhs.get();
  80. }
  81. };
  82. // Symbian compilation can be done with wchar_t being either a native
  83. // type or a typedef. Using Google Mock with OpenC without wchar_t
  84. // should require the definition of _STLP_NO_WCHAR_T.
  85. //
  86. // MSVC treats wchar_t as a native type usually, but treats it as the
  87. // same as unsigned short when the compiler option /Zc:wchar_t- is
  88. // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
  89. // is a native type.
  90. #if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
  91. (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
  92. // wchar_t is a typedef.
  93. #else
  94. # define GMOCK_WCHAR_T_IS_NATIVE_ 1
  95. #endif
  96. // signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
  97. // Using them is a bad practice and not portable. So DON'T use them.
  98. //
  99. // Still, Google Mock is designed to work even if the user uses signed
  100. // wchar_t or unsigned wchar_t (obviously, assuming the compiler
  101. // supports them).
  102. //
  103. // To gcc,
  104. // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
  105. #ifdef __GNUC__
  106. // signed/unsigned wchar_t are valid types.
  107. # define GMOCK_HAS_SIGNED_WCHAR_T_ 1
  108. #endif
  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.
  114. enum TypeKind {
  115. kBool, kInteger, kFloatingPoint, kOther
  116. };
  117. // KindOf<T>::value is the kind of type T.
  118. template <typename T> struct KindOf {
  119. enum { value = kOther }; // The default kind.
  120. };
  121. // This macro declares that the kind of 'type' is 'kind'.
  122. #define GMOCK_DECLARE_KIND_(type, kind) \
  123. template <> struct KindOf<type> { enum { value = kind }; }
  124. GMOCK_DECLARE_KIND_(bool, kBool);
  125. // All standard integer types.
  126. GMOCK_DECLARE_KIND_(char, kInteger);
  127. GMOCK_DECLARE_KIND_(signed char, kInteger);
  128. GMOCK_DECLARE_KIND_(unsigned char, kInteger);
  129. GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
  130. GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
  131. GMOCK_DECLARE_KIND_(int, kInteger);
  132. GMOCK_DECLARE_KIND_(unsigned int, kInteger);
  133. GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
  134. GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
  135. #if GMOCK_WCHAR_T_IS_NATIVE_
  136. GMOCK_DECLARE_KIND_(wchar_t, kInteger);
  137. #endif
  138. // Non-standard integer types.
  139. GMOCK_DECLARE_KIND_(Int64, kInteger);
  140. GMOCK_DECLARE_KIND_(UInt64, kInteger);
  141. // All standard floating-point types.
  142. GMOCK_DECLARE_KIND_(float, kFloatingPoint);
  143. GMOCK_DECLARE_KIND_(double, kFloatingPoint);
  144. GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
  145. #undef GMOCK_DECLARE_KIND_
  146. // Evaluates to the kind of 'type'.
  147. #define GMOCK_KIND_OF_(type) \
  148. static_cast< ::testing::internal::TypeKind>( \
  149. ::testing::internal::KindOf<type>::value)
  150. // Evaluates to true iff integer type T is signed.
  151. #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
  152. // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
  153. // is true iff arithmetic type From can be losslessly converted to
  154. // arithmetic type To.
  155. //
  156. // It's the user's responsibility to ensure that both From and To are
  157. // raw (i.e. has no CV modifier, is not a pointer, and is not a
  158. // reference) built-in arithmetic types, kFromKind is the kind of
  159. // From, and kToKind is the kind of To; the value is
  160. // implementation-defined when the above pre-condition is violated.
  161. template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
  162. struct LosslessArithmeticConvertibleImpl : public false_type {};
  163. // Converting bool to bool is lossless.
  164. template <>
  165. struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
  166. : public true_type {}; // NOLINT
  167. // Converting bool to any integer type is lossless.
  168. template <typename To>
  169. struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
  170. : public true_type {}; // NOLINT
  171. // Converting bool to any floating-point type is lossless.
  172. template <typename To>
  173. struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
  174. : public true_type {}; // NOLINT
  175. // Converting an integer to bool is lossy.
  176. template <typename From>
  177. struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
  178. : public false_type {}; // NOLINT
  179. // Converting an integer to another non-bool integer is lossless iff
  180. // the target type's range encloses the source type's range.
  181. template <typename From, typename To>
  182. struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
  183. : public bool_constant<
  184. // When converting from a smaller size to a larger size, we are
  185. // fine as long as we are not converting from signed to unsigned.
  186. ((sizeof(From) < sizeof(To)) &&
  187. (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
  188. // When converting between the same size, the signedness must match.
  189. ((sizeof(From) == sizeof(To)) &&
  190. (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
  191. #undef GMOCK_IS_SIGNED_
  192. // Converting an integer to a floating-point type may be lossy, since
  193. // the format of a floating-point number is implementation-defined.
  194. template <typename From, typename To>
  195. struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
  196. : public false_type {}; // NOLINT
  197. // Converting a floating-point to bool is lossy.
  198. template <typename From>
  199. struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
  200. : public false_type {}; // NOLINT
  201. // Converting a floating-point to an integer is lossy.
  202. template <typename From, typename To>
  203. struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
  204. : public false_type {}; // NOLINT
  205. // Converting a floating-point to another floating-point is lossless
  206. // iff the target type is at least as big as the source type.
  207. template <typename From, typename To>
  208. struct LosslessArithmeticConvertibleImpl<
  209. kFloatingPoint, From, kFloatingPoint, To>
  210. : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
  211. // LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
  212. // type From can be losslessly converted to arithmetic type To.
  213. //
  214. // It's the user's responsibility to ensure that both From and To are
  215. // raw (i.e. has no CV modifier, is not a pointer, and is not a
  216. // reference) built-in arithmetic types; the value is
  217. // implementation-defined when the above pre-condition is violated.
  218. template <typename From, typename To>
  219. struct LosslessArithmeticConvertible
  220. : public LosslessArithmeticConvertibleImpl<
  221. GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
  222. // This interface knows how to report a Google Mock failure (either
  223. // non-fatal or fatal).
  224. class FailureReporterInterface {
  225. public:
  226. // The type of a failure (either non-fatal or fatal).
  227. enum FailureType {
  228. kNonfatal, kFatal
  229. };
  230. virtual ~FailureReporterInterface() {}
  231. // Reports a failure that occurred at the given source file location.
  232. virtual void ReportFailure(FailureType type, const char* file, int line,
  233. const string& message) = 0;
  234. };
  235. // Returns the failure reporter used by Google Mock.
  236. GTEST_API_ FailureReporterInterface* GetFailureReporter();
  237. // Asserts that condition is true; aborts the process with the given
  238. // message if condition is false. We cannot use LOG(FATAL) or CHECK()
  239. // as Google Mock might be used to mock the log sink itself. We
  240. // inline this function to prevent it from showing up in the stack
  241. // trace.
  242. inline void Assert(bool condition, const char* file, int line,
  243. const string& msg) {
  244. if (!condition) {
  245. GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
  246. file, line, msg);
  247. }
  248. }
  249. inline void Assert(bool condition, const char* file, int line) {
  250. Assert(condition, file, line, "Assertion failed.");
  251. }
  252. // Verifies that condition is true; generates a non-fatal failure if
  253. // condition is false.
  254. inline void Expect(bool condition, const char* file, int line,
  255. const string& msg) {
  256. if (!condition) {
  257. GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
  258. file, line, msg);
  259. }
  260. }
  261. inline void Expect(bool condition, const char* file, int line) {
  262. Expect(condition, file, line, "Expectation failed.");
  263. }
  264. // Severity level of a log.
  265. enum LogSeverity {
  266. kInfo = 0,
  267. kWarning = 1
  268. };
  269. // Valid values for the --gmock_verbose flag.
  270. // All logs (informational and warnings) are printed.
  271. const char kInfoVerbosity[] = "info";
  272. // Only warnings are printed.
  273. const char kWarningVerbosity[] = "warning";
  274. // No logs are printed.
  275. const char kErrorVerbosity[] = "error";
  276. // Returns true iff a log with the given severity is visible according
  277. // to the --gmock_verbose flag.
  278. GTEST_API_ bool LogIsVisible(LogSeverity severity);
  279. // Prints the given message to stdout iff 'severity' >= the level
  280. // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
  281. // 0, also prints the stack trace excluding the top
  282. // stack_frames_to_skip frames. In opt mode, any positive
  283. // stack_frames_to_skip is treated as 0, since we don't know which
  284. // function calls will be inlined by the compiler and need to be
  285. // conservative.
  286. GTEST_API_ void Log(LogSeverity severity,
  287. const string& message,
  288. int stack_frames_to_skip);
  289. // TODO(wan@google.com): group all type utilities together.
  290. // Type traits.
  291. // is_reference<T>::value is non-zero iff T is a reference type.
  292. template <typename T> struct is_reference : public false_type {};
  293. template <typename T> struct is_reference<T&> : public true_type {};
  294. // type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
  295. template <typename T1, typename T2> struct type_equals : public false_type {};
  296. template <typename T> struct type_equals<T, T> : public true_type {};
  297. // remove_reference<T>::type removes the reference from type T, if any.
  298. template <typename T> struct remove_reference { typedef T type; }; // NOLINT
  299. template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
  300. // DecayArray<T>::type turns an array type U[N] to const U* and preserves
  301. // other types. Useful for saving a copy of a function argument.
  302. template <typename T> struct DecayArray { typedef T type; }; // NOLINT
  303. template <typename T, size_t N> struct DecayArray<T[N]> {
  304. typedef const T* type;
  305. };
  306. // Sometimes people use arrays whose size is not available at the use site
  307. // (e.g. extern const char kNamePrefix[]). This specialization covers that
  308. // case.
  309. template <typename T> struct DecayArray<T[]> {
  310. typedef const T* type;
  311. };
  312. // Disable MSVC warnings for infinite recursion, since in this case the
  313. // the recursion is unreachable.
  314. #ifdef _MSC_VER
  315. # pragma warning(push)
  316. # pragma warning(disable:4717)
  317. #endif
  318. // Invalid<T>() is usable as an expression of type T, but will terminate
  319. // the program with an assertion failure if actually run. This is useful
  320. // when a value of type T is needed for compilation, but the statement
  321. // will not really be executed (or we don't care if the statement
  322. // crashes).
  323. template <typename T>
  324. inline T Invalid() {
  325. Assert(false, "", -1, "Internal error: attempt to return invalid value");
  326. // This statement is unreachable, and would never terminate even if it
  327. // could be reached. It is provided only to placate compiler warnings
  328. // about missing return statements.
  329. return Invalid<T>();
  330. }
  331. #ifdef _MSC_VER
  332. # pragma warning(pop)
  333. #endif
  334. // Given a raw type (i.e. having no top-level reference or const
  335. // modifier) RawContainer that's either an STL-style container or a
  336. // native array, class StlContainerView<RawContainer> has the
  337. // following members:
  338. //
  339. // - type is a type that provides an STL-style container view to
  340. // (i.e. implements the STL container concept for) RawContainer;
  341. // - const_reference is a type that provides a reference to a const
  342. // RawContainer;
  343. // - ConstReference(raw_container) returns a const reference to an STL-style
  344. // container view to raw_container, which is a RawContainer.
  345. // - Copy(raw_container) returns an STL-style container view of a
  346. // copy of raw_container, which is a RawContainer.
  347. //
  348. // This generic version is used when RawContainer itself is already an
  349. // STL-style container.
  350. template <class RawContainer>
  351. class StlContainerView {
  352. public:
  353. typedef RawContainer type;
  354. typedef const type& const_reference;
  355. static const_reference ConstReference(const RawContainer& container) {
  356. // Ensures that RawContainer is not a const type.
  357. testing::StaticAssertTypeEq<RawContainer,
  358. GTEST_REMOVE_CONST_(RawContainer)>();
  359. return container;
  360. }
  361. static type Copy(const RawContainer& container) { return container; }
  362. };
  363. // This specialization is used when RawContainer is a native array type.
  364. template <typename Element, size_t N>
  365. class StlContainerView<Element[N]> {
  366. public:
  367. typedef GTEST_REMOVE_CONST_(Element) RawElement;
  368. typedef internal::NativeArray<RawElement> type;
  369. // NativeArray<T> can represent a native array either by value or by
  370. // reference (selected by a constructor argument), so 'const type'
  371. // can be used to reference a const native array. We cannot
  372. // 'typedef const type& const_reference' here, as that would mean
  373. // ConstReference() has to return a reference to a local variable.
  374. typedef const type const_reference;
  375. static const_reference ConstReference(const Element (&array)[N]) {
  376. // Ensures that Element is not a const type.
  377. testing::StaticAssertTypeEq<Element, RawElement>();
  378. #if GTEST_OS_SYMBIAN
  379. // The Nokia Symbian compiler confuses itself in template instantiation
  380. // for this call without the cast to Element*:
  381. // function call '[testing::internal::NativeArray<char *>].NativeArray(
  382. // {lval} const char *[4], long, testing::internal::RelationToSource)'
  383. // does not match
  384. // 'testing::internal::NativeArray<char *>::NativeArray(
  385. // char *const *, unsigned int, testing::internal::RelationToSource)'
  386. // (instantiating: 'testing::internal::ContainsMatcherImpl
  387. // <const char * (&)[4]>::Matches(const char * (&)[4]) const')
  388. // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
  389. // ConstReference(const char * (&)[4])')
  390. // (and though the N parameter type is mismatched in the above explicit
  391. // conversion of it doesn't help - only the conversion of the array).
  392. return type(const_cast<Element*>(&array[0]), N,
  393. RelationToSourceReference());
  394. #else
  395. return type(array, N, RelationToSourceReference());
  396. #endif // GTEST_OS_SYMBIAN
  397. }
  398. static type Copy(const Element (&array)[N]) {
  399. #if GTEST_OS_SYMBIAN
  400. return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
  401. #else
  402. return type(array, N, RelationToSourceCopy());
  403. #endif // GTEST_OS_SYMBIAN
  404. }
  405. };
  406. // This specialization is used when RawContainer is a native array
  407. // represented as a (pointer, size) tuple.
  408. template <typename ElementPointer, typename Size>
  409. class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
  410. public:
  411. typedef GTEST_REMOVE_CONST_(
  412. typename internal::PointeeOf<ElementPointer>::type) RawElement;
  413. typedef internal::NativeArray<RawElement> type;
  414. typedef const type const_reference;
  415. static const_reference ConstReference(
  416. const ::testing::tuple<ElementPointer, Size>& array) {
  417. return type(get<0>(array), get<1>(array), RelationToSourceReference());
  418. }
  419. static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
  420. return type(get<0>(array), get<1>(array), RelationToSourceCopy());
  421. }
  422. };
  423. // The following specialization prevents the user from instantiating
  424. // StlContainer with a reference type.
  425. template <typename T> class StlContainerView<T&>;
  426. // A type transform to remove constness from the first part of a pair.
  427. // Pairs like that are used as the value_type of associative containers,
  428. // and this transform produces a similar but assignable pair.
  429. template <typename T>
  430. struct RemoveConstFromKey {
  431. typedef T type;
  432. };
  433. // Partially specialized to remove constness from std::pair<const K, V>.
  434. template <typename K, typename V>
  435. struct RemoveConstFromKey<std::pair<const K, V> > {
  436. typedef std::pair<K, V> type;
  437. };
  438. // Mapping from booleans to types. Similar to boost::bool_<kValue> and
  439. // std::integral_constant<bool, kValue>.
  440. template <bool kValue>
  441. struct BooleanConstant {};
  442. } // namespace internal
  443. } // namespace testing
  444. #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_