gmock-internal-utils.h 19 KB

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