gmock-internal-utils.h 18 KB

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