gmock-internal-utils.h 20 KB

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