gmock-internal-utils.h 19 KB

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