gmock-internal-utils.h 19 KB

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