Path: blob/main/contrib/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h
48524 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file defines some utilities useful for implementing Google32// Mock. They are subject to change without notice, so please DO NOT33// USE THEM IN USER CODE.3435// IWYU pragma: private, include "gmock/gmock.h"36// IWYU pragma: friend gmock/.*3738#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_39#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_4041#include <stdio.h>4243#include <ostream> // NOLINT44#include <string>45#include <type_traits>46#include <utility>47#include <vector>4849#include "gmock/internal/gmock-port.h"50#include "gtest/gtest.h"5152namespace testing {5354template <typename>55class Matcher;5657namespace internal {5859// Silence MSVC C4100 (unreferenced formal parameter) and60// C4805('==': unsafe mix of type 'const int' and type 'const bool')61GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)6263// Joins a vector of strings as if they are fields of a tuple; returns64// the joined string.65GTEST_API_ std::string JoinAsKeyValueTuple(66const std::vector<const char*>& names, const Strings& values);6768// Converts an identifier name to a space-separated list of lower-case69// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is70// treated as one word. For example, both "FooBar123" and71// "foo_bar_123" are converted to "foo bar 123".72GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);7374// GetRawPointer(p) returns the raw pointer underlying p when p is a75// smart pointer, or returns p itself when p is already a raw pointer.76// The following default implementation is for the smart pointer case.77template <typename Pointer>78inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {79return p.get();80}81// This overload version is for std::reference_wrapper, which does not work with82// the overload above, as it does not have an `element_type`.83template <typename Element>84inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {85return &r.get();86}8788// This overloaded version is for the raw pointer case.89template <typename Element>90inline Element* GetRawPointer(Element* p) {91return p;92}9394// Default definitions for all compilers.95// NOTE: If you implement support for other compilers, make sure to avoid96// unexpected overlaps.97// (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)98#define GMOCK_INTERNAL_WARNING_PUSH()99#define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)100#define GMOCK_INTERNAL_WARNING_POP()101102#if defined(__clang__)103#undef GMOCK_INTERNAL_WARNING_PUSH104#define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")105#undef GMOCK_INTERNAL_WARNING_CLANG106#define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \107_Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))108#undef GMOCK_INTERNAL_WARNING_POP109#define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")110#endif111112// MSVC treats wchar_t as a native type usually, but treats it as the113// same as unsigned short when the compiler option /Zc:wchar_t- is114// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t115// is a native type.116#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)117// wchar_t is a typedef.118#else119#define GMOCK_WCHAR_T_IS_NATIVE_ 1120#endif121122// In what follows, we use the term "kind" to indicate whether a type123// is bool, an integer type (excluding bool), a floating-point type,124// or none of them. This categorization is useful for determining125// when a matcher argument type can be safely converted to another126// type in the implementation of SafeMatcherCast.127enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };128129// KindOf<T>::value is the kind of type T.130template <typename T>131struct KindOf {132enum { value = kOther }; // The default kind.133};134135// This macro declares that the kind of 'type' is 'kind'.136#define GMOCK_DECLARE_KIND_(type, kind) \137template <> \138struct KindOf<type> { \139enum { value = kind }; \140}141142GMOCK_DECLARE_KIND_(bool, kBool);143144// All standard integer types.145GMOCK_DECLARE_KIND_(char, kInteger);146GMOCK_DECLARE_KIND_(signed char, kInteger);147GMOCK_DECLARE_KIND_(unsigned char, kInteger);148GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT149GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT150GMOCK_DECLARE_KIND_(int, kInteger);151GMOCK_DECLARE_KIND_(unsigned int, kInteger);152GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT153GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT154GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT155GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT156157#if GMOCK_WCHAR_T_IS_NATIVE_158GMOCK_DECLARE_KIND_(wchar_t, kInteger);159#endif160161// All standard floating-point types.162GMOCK_DECLARE_KIND_(float, kFloatingPoint);163GMOCK_DECLARE_KIND_(double, kFloatingPoint);164GMOCK_DECLARE_KIND_(long double, kFloatingPoint);165166#undef GMOCK_DECLARE_KIND_167168// Evaluates to the kind of 'type'.169#define GMOCK_KIND_OF_(type) \170static_cast< ::testing::internal::TypeKind>( \171::testing::internal::KindOf<type>::value)172173// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value174// is true if and only if arithmetic type From can be losslessly converted to175// arithmetic type To.176//177// It's the user's responsibility to ensure that both From and To are178// raw (i.e. has no CV modifier, is not a pointer, and is not a179// reference) built-in arithmetic types, kFromKind is the kind of180// From, and kToKind is the kind of To; the value is181// implementation-defined when the above pre-condition is violated.182template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>183using LosslessArithmeticConvertibleImpl = std::integral_constant<184bool,185// clang-format off186// Converting from bool is always lossless187(kFromKind == kBool) ? true188// Converting between any other type kinds will be lossy if the type189// kinds are not the same.190: (kFromKind != kToKind) ? false191: (kFromKind == kInteger &&192// Converting between integers of different widths is allowed so long193// as the conversion does not go from signed to unsigned.194(((sizeof(From) < sizeof(To)) &&195!(std::is_signed<From>::value && !std::is_signed<To>::value)) ||196// Converting between integers of the same width only requires the197// two types to have the same signedness.198((sizeof(From) == sizeof(To)) &&199(std::is_signed<From>::value == std::is_signed<To>::value)))200) ? true201// Floating point conversions are lossless if and only if `To` is at least202// as wide as `From`.203: (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true204: false205// clang-format on206>;207208// LosslessArithmeticConvertible<From, To>::value is true if and only if209// arithmetic type From can be losslessly converted to arithmetic type To.210//211// It's the user's responsibility to ensure that both From and To are212// raw (i.e. has no CV modifier, is not a pointer, and is not a213// reference) built-in arithmetic types; the value is214// implementation-defined when the above pre-condition is violated.215template <typename From, typename To>216using LosslessArithmeticConvertible =217LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,218GMOCK_KIND_OF_(To), To>;219220// This interface knows how to report a Google Mock failure (either221// non-fatal or fatal).222class FailureReporterInterface {223public:224// The type of a failure (either non-fatal or fatal).225enum FailureType { kNonfatal, kFatal };226227virtual ~FailureReporterInterface() = default;228229// Reports a failure that occurred at the given source file location.230virtual void ReportFailure(FailureType type, const char* file, int line,231const std::string& message) = 0;232};233234// Returns the failure reporter used by Google Mock.235GTEST_API_ FailureReporterInterface* GetFailureReporter();236237// Asserts that condition is true; aborts the process with the given238// message if condition is false. We cannot use LOG(FATAL) or CHECK()239// as Google Mock might be used to mock the log sink itself. We240// inline this function to prevent it from showing up in the stack241// trace.242inline void Assert(bool condition, const char* file, int line,243const std::string& msg) {244if (!condition) {245GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,246line, msg);247}248}249inline void Assert(bool condition, const char* file, int line) {250Assert(condition, file, line, "Assertion failed.");251}252253// Verifies that condition is true; generates a non-fatal failure if254// condition is false.255inline void Expect(bool condition, const char* file, int line,256const std::string& msg) {257if (!condition) {258GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,259file, line, msg);260}261}262inline void Expect(bool condition, const char* file, int line) {263Expect(condition, file, line, "Expectation failed.");264}265266// Severity level of a log.267enum LogSeverity { kInfo = 0, kWarning = 1 };268269// Valid values for the --gmock_verbose flag.270271// All logs (informational and warnings) are printed.272const char kInfoVerbosity[] = "info";273// Only warnings are printed.274const char kWarningVerbosity[] = "warning";275// No logs are printed.276const char kErrorVerbosity[] = "error";277278// Returns true if and only if a log with the given severity is visible279// according to the --gmock_verbose flag.280GTEST_API_ bool LogIsVisible(LogSeverity severity);281282// Prints the given message to stdout if and only if 'severity' >= the level283// specified by the --gmock_verbose flag. If stack_frames_to_skip >=284// 0, also prints the stack trace excluding the top285// stack_frames_to_skip frames. In opt mode, any positive286// stack_frames_to_skip is treated as 0, since we don't know which287// function calls will be inlined by the compiler and need to be288// conservative.289GTEST_API_ void Log(LogSeverity severity, const std::string& message,290int stack_frames_to_skip);291292// A marker class that is used to resolve parameterless expectations to the293// correct overload. This must not be instantiable, to prevent client code from294// accidentally resolving to the overload; for example:295//296// ON_CALL(mock, Method({}, nullptr))...297//298class WithoutMatchers {299private:300WithoutMatchers() {}301friend GTEST_API_ WithoutMatchers GetWithoutMatchers();302};303304// Internal use only: access the singleton instance of WithoutMatchers.305GTEST_API_ WithoutMatchers GetWithoutMatchers();306307// Invalid<T>() is usable as an expression of type T, but will terminate308// the program with an assertion failure if actually run. This is useful309// when a value of type T is needed for compilation, but the statement310// will not really be executed (or we don't care if the statement311// crashes).312template <typename T>313inline T Invalid() {314Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,315"Internal error: attempt to return invalid value");316#if defined(__GNUC__) || defined(__clang__)317__builtin_unreachable();318#elif defined(_MSC_VER)319__assume(0);320#else321return Invalid<T>();322#endif323}324325// Given a raw type (i.e. having no top-level reference or const326// modifier) RawContainer that's either an STL-style container or a327// native array, class StlContainerView<RawContainer> has the328// following members:329//330// - type is a type that provides an STL-style container view to331// (i.e. implements the STL container concept for) RawContainer;332// - const_reference is a type that provides a reference to a const333// RawContainer;334// - ConstReference(raw_container) returns a const reference to an STL-style335// container view to raw_container, which is a RawContainer.336// - Copy(raw_container) returns an STL-style container view of a337// copy of raw_container, which is a RawContainer.338//339// This generic version is used when RawContainer itself is already an340// STL-style container.341template <class RawContainer>342class StlContainerView {343public:344typedef RawContainer type;345typedef const type& const_reference;346347static const_reference ConstReference(const RawContainer& container) {348static_assert(!std::is_const<RawContainer>::value,349"RawContainer type must not be const");350return container;351}352static type Copy(const RawContainer& container) { return container; }353};354355// This specialization is used when RawContainer is a native array type.356template <typename Element, size_t N>357class StlContainerView<Element[N]> {358public:359typedef typename std::remove_const<Element>::type RawElement;360typedef internal::NativeArray<RawElement> type;361// NativeArray<T> can represent a native array either by value or by362// reference (selected by a constructor argument), so 'const type'363// can be used to reference a const native array. We cannot364// 'typedef const type& const_reference' here, as that would mean365// ConstReference() has to return a reference to a local variable.366typedef const type const_reference;367368static const_reference ConstReference(const Element (&array)[N]) {369static_assert(std::is_same<Element, RawElement>::value,370"Element type must not be const");371return type(array, N, RelationToSourceReference());372}373static type Copy(const Element (&array)[N]) {374return type(array, N, RelationToSourceCopy());375}376};377378// This specialization is used when RawContainer is a native array379// represented as a (pointer, size) tuple.380template <typename ElementPointer, typename Size>381class StlContainerView< ::std::tuple<ElementPointer, Size> > {382public:383typedef typename std::remove_const<384typename std::pointer_traits<ElementPointer>::element_type>::type385RawElement;386typedef internal::NativeArray<RawElement> type;387typedef const type const_reference;388389static const_reference ConstReference(390const ::std::tuple<ElementPointer, Size>& array) {391return type(std::get<0>(array), std::get<1>(array),392RelationToSourceReference());393}394static type Copy(const ::std::tuple<ElementPointer, Size>& array) {395return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());396}397};398399// The following specialization prevents the user from instantiating400// StlContainer with a reference type.401template <typename T>402class StlContainerView<T&>;403404// A type transform to remove constness from the first part of a pair.405// Pairs like that are used as the value_type of associative containers,406// and this transform produces a similar but assignable pair.407template <typename T>408struct RemoveConstFromKey {409typedef T type;410};411412// Partially specialized to remove constness from std::pair<const K, V>.413template <typename K, typename V>414struct RemoveConstFromKey<std::pair<const K, V> > {415typedef std::pair<K, V> type;416};417418// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to419// reduce code size.420GTEST_API_ void IllegalDoDefault(const char* file, int line);421422template <typename F, typename Tuple, size_t... Idx>423auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>)424-> decltype(std::forward<F>(f)(425std::get<Idx>(std::forward<Tuple>(args))...)) {426return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);427}428429// Apply the function to a tuple of arguments.430template <typename F, typename Tuple>431auto Apply(F&& f, Tuple&& args)432-> decltype(ApplyImpl(433std::forward<F>(f), std::forward<Tuple>(args),434std::make_index_sequence<std::tuple_size<435typename std::remove_reference<Tuple>::type>::value>())) {436return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),437std::make_index_sequence<std::tuple_size<438typename std::remove_reference<Tuple>::type>::value>());439}440441// Template struct Function<F>, where F must be a function type, contains442// the following typedefs:443//444// Result: the function's return type.445// Arg<N>: the type of the N-th argument, where N starts with 0.446// ArgumentTuple: the tuple type consisting of all parameters of F.447// ArgumentMatcherTuple: the tuple type consisting of Matchers for all448// parameters of F.449// MakeResultVoid: the function type obtained by substituting void450// for the return type of F.451// MakeResultIgnoredValue:452// the function type obtained by substituting Something453// for the return type of F.454template <typename T>455struct Function;456457template <typename R, typename... Args>458struct Function<R(Args...)> {459using Result = R;460static constexpr size_t ArgumentCount = sizeof...(Args);461template <size_t I>462using Arg = ElemFromList<I, Args...>;463using ArgumentTuple = std::tuple<Args...>;464using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;465using MakeResultVoid = void(Args...);466using MakeResultIgnoredValue = IgnoredValue(Args...);467};468469#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL470template <typename R, typename... Args>471constexpr size_t Function<R(Args...)>::ArgumentCount;472#endif473474// Workaround for MSVC error C2039: 'type': is not a member of 'std'475// when std::tuple_element is used.476// See: https://github.com/google/googletest/issues/3931477// Can be replaced with std::tuple_element_t in C++14.478template <size_t I, typename T>479using TupleElement = typename std::tuple_element<I, T>::type;480481bool Base64Unescape(const std::string& encoded, std::string* decoded);482483GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4805484485} // namespace internal486} // namespace testing487488#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_489490491