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