Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 09:00:24

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 
0030 // Google Mock - a framework for writing C++ mock classes.
0031 //
0032 // This file defines some utilities useful for implementing Google
0033 // Mock.  They are subject to change without notice, so please DO NOT
0034 // USE THEM IN USER CODE.
0035 
0036 // IWYU pragma: private, include "gmock/gmock.h"
0037 // IWYU pragma: friend gmock/.*
0038 
0039 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
0040 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
0041 
0042 #include <stdio.h>
0043 
0044 #include <ostream>  // NOLINT
0045 #include <string>
0046 #include <type_traits>
0047 #include <utility>
0048 #include <vector>
0049 
0050 #include "gmock/internal/gmock-port.h"
0051 #include "gtest/gtest.h"
0052 
0053 namespace testing {
0054 
0055 template <typename>
0056 class Matcher;
0057 
0058 namespace internal {
0059 
0060 // Silence MSVC C4100 (unreferenced formal parameter) and
0061 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
0062 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)
0063 
0064 // Joins a vector of strings as if they are fields of a tuple; returns
0065 // the joined string.
0066 GTEST_API_ std::string JoinAsKeyValueTuple(
0067     const std::vector<const char*>& names, const Strings& values);
0068 
0069 // Converts an identifier name to a space-separated list of lower-case
0070 // words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
0071 // treated as one word.  For example, both "FooBar123" and
0072 // "foo_bar_123" are converted to "foo bar 123".
0073 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
0074 
0075 // GetRawPointer(p) returns the raw pointer underlying p when p is a
0076 // smart pointer, or returns p itself when p is already a raw pointer.
0077 // The following default implementation is for the smart pointer case.
0078 template <typename Pointer>
0079 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
0080   return p.get();
0081 }
0082 // This overload version is for std::reference_wrapper, which does not work with
0083 // the overload above, as it does not have an `element_type`.
0084 template <typename Element>
0085 inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
0086   return &r.get();
0087 }
0088 
0089 // This overloaded version is for the raw pointer case.
0090 template <typename Element>
0091 inline Element* GetRawPointer(Element* p) {
0092   return p;
0093 }
0094 
0095 // Default definitions for all compilers.
0096 // NOTE: If you implement support for other compilers, make sure to avoid
0097 // unexpected overlaps.
0098 // (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)
0099 #define GMOCK_INTERNAL_WARNING_PUSH()
0100 #define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)
0101 #define GMOCK_INTERNAL_WARNING_POP()
0102 
0103 #if defined(__clang__)
0104 #undef GMOCK_INTERNAL_WARNING_PUSH
0105 #define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")
0106 #undef GMOCK_INTERNAL_WARNING_CLANG
0107 #define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \
0108   _Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))
0109 #undef GMOCK_INTERNAL_WARNING_POP
0110 #define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")
0111 #endif
0112 
0113 // MSVC treats wchar_t as a native type usually, but treats it as the
0114 // same as unsigned short when the compiler option /Zc:wchar_t- is
0115 // specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
0116 // is a native type.
0117 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
0118 // wchar_t is a typedef.
0119 #else
0120 #define GMOCK_WCHAR_T_IS_NATIVE_ 1
0121 #endif
0122 
0123 // In what follows, we use the term "kind" to indicate whether a type
0124 // is bool, an integer type (excluding bool), a floating-point type,
0125 // or none of them.  This categorization is useful for determining
0126 // when a matcher argument type can be safely converted to another
0127 // type in the implementation of SafeMatcherCast.
0128 enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
0129 
0130 // KindOf<T>::value is the kind of type T.
0131 template <typename T>
0132 struct KindOf {
0133   enum { value = kOther };  // The default kind.
0134 };
0135 
0136 // This macro declares that the kind of 'type' is 'kind'.
0137 #define GMOCK_DECLARE_KIND_(type, kind) \
0138   template <>                           \
0139   struct KindOf<type> {                 \
0140     enum { value = kind };              \
0141   }
0142 
0143 GMOCK_DECLARE_KIND_(bool, kBool);
0144 
0145 // All standard integer types.
0146 GMOCK_DECLARE_KIND_(char, kInteger);
0147 GMOCK_DECLARE_KIND_(signed char, kInteger);
0148 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
0149 GMOCK_DECLARE_KIND_(short, kInteger);           // NOLINT
0150 GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
0151 GMOCK_DECLARE_KIND_(int, kInteger);
0152 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
0153 GMOCK_DECLARE_KIND_(long, kInteger);                // NOLINT
0154 GMOCK_DECLARE_KIND_(unsigned long, kInteger);       // NOLINT
0155 GMOCK_DECLARE_KIND_(long long, kInteger);           // NOLINT
0156 GMOCK_DECLARE_KIND_(unsigned long long, kInteger);  // NOLINT
0157 
0158 #if GMOCK_WCHAR_T_IS_NATIVE_
0159 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
0160 #endif
0161 
0162 // All standard floating-point types.
0163 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
0164 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
0165 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
0166 
0167 #undef GMOCK_DECLARE_KIND_
0168 
0169 // Evaluates to the kind of 'type'.
0170 #define GMOCK_KIND_OF_(type)                   \
0171   static_cast< ::testing::internal::TypeKind>( \
0172       ::testing::internal::KindOf<type>::value)
0173 
0174 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
0175 // is true if and only if arithmetic type From can be losslessly converted to
0176 // arithmetic type To.
0177 //
0178 // It's the user's responsibility to ensure that both From and To are
0179 // raw (i.e. has no CV modifier, is not a pointer, and is not a
0180 // reference) built-in arithmetic types, kFromKind is the kind of
0181 // From, and kToKind is the kind of To; the value is
0182 // implementation-defined when the above pre-condition is violated.
0183 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
0184 using LosslessArithmeticConvertibleImpl = std::integral_constant<
0185     bool,
0186     // clang-format off
0187       // Converting from bool is always lossless
0188       (kFromKind == kBool) ? true
0189       // Converting between any other type kinds will be lossy if the type
0190       // kinds are not the same.
0191     : (kFromKind != kToKind) ? false
0192     : (kFromKind == kInteger &&
0193        // Converting between integers of different widths is allowed so long
0194        // as the conversion does not go from signed to unsigned.
0195       (((sizeof(From) < sizeof(To)) &&
0196         !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
0197        // Converting between integers of the same width only requires the
0198        // two types to have the same signedness.
0199        ((sizeof(From) == sizeof(To)) &&
0200         (std::is_signed<From>::value == std::is_signed<To>::value)))
0201        ) ? true
0202       // Floating point conversions are lossless if and only if `To` is at least
0203       // as wide as `From`.
0204     : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
0205     : false
0206     // clang-format on
0207     >;
0208 
0209 // LosslessArithmeticConvertible<From, To>::value is true if and only if
0210 // arithmetic type From can be losslessly converted to arithmetic type To.
0211 //
0212 // It's the user's responsibility to ensure that both From and To are
0213 // raw (i.e. has no CV modifier, is not a pointer, and is not a
0214 // reference) built-in arithmetic types; the value is
0215 // implementation-defined when the above pre-condition is violated.
0216 template <typename From, typename To>
0217 using LosslessArithmeticConvertible =
0218     LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
0219                                       GMOCK_KIND_OF_(To), To>;
0220 
0221 // This interface knows how to report a Google Mock failure (either
0222 // non-fatal or fatal).
0223 class FailureReporterInterface {
0224  public:
0225   // The type of a failure (either non-fatal or fatal).
0226   enum FailureType { kNonfatal, kFatal };
0227 
0228   virtual ~FailureReporterInterface() = default;
0229 
0230   // Reports a failure that occurred at the given source file location.
0231   virtual void ReportFailure(FailureType type, const char* file, int line,
0232                              const std::string& message) = 0;
0233 };
0234 
0235 // Returns the failure reporter used by Google Mock.
0236 GTEST_API_ FailureReporterInterface* GetFailureReporter();
0237 
0238 // Asserts that condition is true; aborts the process with the given
0239 // message if condition is false.  We cannot use LOG(FATAL) or CHECK()
0240 // as Google Mock might be used to mock the log sink itself.  We
0241 // inline this function to prevent it from showing up in the stack
0242 // trace.
0243 inline void Assert(bool condition, const char* file, int line,
0244                    const std::string& msg) {
0245   if (!condition) {
0246     GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
0247                                         line, msg);
0248   }
0249 }
0250 inline void Assert(bool condition, const char* file, int line) {
0251   Assert(condition, file, line, "Assertion failed.");
0252 }
0253 
0254 // Verifies that condition is true; generates a non-fatal failure if
0255 // condition is false.
0256 inline void Expect(bool condition, const char* file, int line,
0257                    const std::string& msg) {
0258   if (!condition) {
0259     GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
0260                                         file, line, msg);
0261   }
0262 }
0263 inline void Expect(bool condition, const char* file, int line) {
0264   Expect(condition, file, line, "Expectation failed.");
0265 }
0266 
0267 // Severity level of a log.
0268 enum LogSeverity { kInfo = 0, kWarning = 1 };
0269 
0270 // Valid values for the --gmock_verbose flag.
0271 
0272 // All logs (informational and warnings) are printed.
0273 const char kInfoVerbosity[] = "info";
0274 // Only warnings are printed.
0275 const char kWarningVerbosity[] = "warning";
0276 // No logs are printed.
0277 const char kErrorVerbosity[] = "error";
0278 
0279 // Returns true if and only if a log with the given severity is visible
0280 // according to the --gmock_verbose flag.
0281 GTEST_API_ bool LogIsVisible(LogSeverity severity);
0282 
0283 // Prints the given message to stdout if and only if 'severity' >= the level
0284 // specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
0285 // 0, also prints the stack trace excluding the top
0286 // stack_frames_to_skip frames.  In opt mode, any positive
0287 // stack_frames_to_skip is treated as 0, since we don't know which
0288 // function calls will be inlined by the compiler and need to be
0289 // conservative.
0290 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
0291                     int stack_frames_to_skip);
0292 
0293 // A marker class that is used to resolve parameterless expectations to the
0294 // correct overload. This must not be instantiable, to prevent client code from
0295 // accidentally resolving to the overload; for example:
0296 //
0297 //    ON_CALL(mock, Method({}, nullptr))...
0298 //
0299 class WithoutMatchers {
0300  private:
0301   WithoutMatchers() {}
0302   friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
0303 };
0304 
0305 // Internal use only: access the singleton instance of WithoutMatchers.
0306 GTEST_API_ WithoutMatchers GetWithoutMatchers();
0307 
0308 // Invalid<T>() is usable as an expression of type T, but will terminate
0309 // the program with an assertion failure if actually run.  This is useful
0310 // when a value of type T is needed for compilation, but the statement
0311 // will not really be executed (or we don't care if the statement
0312 // crashes).
0313 template <typename T>
0314 inline T Invalid() {
0315   Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
0316          "Internal error: attempt to return invalid value");
0317 #if defined(__GNUC__) || defined(__clang__)
0318   __builtin_unreachable();
0319 #elif defined(_MSC_VER)
0320   __assume(0);
0321 #else
0322   return Invalid<T>();
0323 #endif
0324 }
0325 
0326 // Given a raw type (i.e. having no top-level reference or const
0327 // modifier) RawContainer that's either an STL-style container or a
0328 // native array, class StlContainerView<RawContainer> has the
0329 // following members:
0330 //
0331 //   - type is a type that provides an STL-style container view to
0332 //     (i.e. implements the STL container concept for) RawContainer;
0333 //   - const_reference is a type that provides a reference to a const
0334 //     RawContainer;
0335 //   - ConstReference(raw_container) returns a const reference to an STL-style
0336 //     container view to raw_container, which is a RawContainer.
0337 //   - Copy(raw_container) returns an STL-style container view of a
0338 //     copy of raw_container, which is a RawContainer.
0339 //
0340 // This generic version is used when RawContainer itself is already an
0341 // STL-style container.
0342 template <class RawContainer>
0343 class StlContainerView {
0344  public:
0345   typedef RawContainer type;
0346   typedef const type& const_reference;
0347 
0348   static const_reference ConstReference(const RawContainer& container) {
0349     static_assert(!std::is_const<RawContainer>::value,
0350                   "RawContainer type must not be const");
0351     return container;
0352   }
0353   static type Copy(const RawContainer& container) { return container; }
0354 };
0355 
0356 // This specialization is used when RawContainer is a native array type.
0357 template <typename Element, size_t N>
0358 class StlContainerView<Element[N]> {
0359  public:
0360   typedef typename std::remove_const<Element>::type RawElement;
0361   typedef internal::NativeArray<RawElement> type;
0362   // NativeArray<T> can represent a native array either by value or by
0363   // reference (selected by a constructor argument), so 'const type'
0364   // can be used to reference a const native array.  We cannot
0365   // 'typedef const type& const_reference' here, as that would mean
0366   // ConstReference() has to return a reference to a local variable.
0367   typedef const type const_reference;
0368 
0369   static const_reference ConstReference(const Element (&array)[N]) {
0370     static_assert(std::is_same<Element, RawElement>::value,
0371                   "Element type must not be const");
0372     return type(array, N, RelationToSourceReference());
0373   }
0374   static type Copy(const Element (&array)[N]) {
0375     return type(array, N, RelationToSourceCopy());
0376   }
0377 };
0378 
0379 // This specialization is used when RawContainer is a native array
0380 // represented as a (pointer, size) tuple.
0381 template <typename ElementPointer, typename Size>
0382 class StlContainerView< ::std::tuple<ElementPointer, Size> > {
0383  public:
0384   typedef typename std::remove_const<
0385       typename std::pointer_traits<ElementPointer>::element_type>::type
0386       RawElement;
0387   typedef internal::NativeArray<RawElement> type;
0388   typedef const type const_reference;
0389 
0390   static const_reference ConstReference(
0391       const ::std::tuple<ElementPointer, Size>& array) {
0392     return type(std::get<0>(array), std::get<1>(array),
0393                 RelationToSourceReference());
0394   }
0395   static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
0396     return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
0397   }
0398 };
0399 
0400 // The following specialization prevents the user from instantiating
0401 // StlContainer with a reference type.
0402 template <typename T>
0403 class StlContainerView<T&>;
0404 
0405 // A type transform to remove constness from the first part of a pair.
0406 // Pairs like that are used as the value_type of associative containers,
0407 // and this transform produces a similar but assignable pair.
0408 template <typename T>
0409 struct RemoveConstFromKey {
0410   typedef T type;
0411 };
0412 
0413 // Partially specialized to remove constness from std::pair<const K, V>.
0414 template <typename K, typename V>
0415 struct RemoveConstFromKey<std::pair<const K, V> > {
0416   typedef std::pair<K, V> type;
0417 };
0418 
0419 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
0420 // reduce code size.
0421 GTEST_API_ void IllegalDoDefault(const char* file, int line);
0422 
0423 template <typename F, typename Tuple, size_t... Idx>
0424 auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>)
0425     -> decltype(std::forward<F>(f)(
0426         std::get<Idx>(std::forward<Tuple>(args))...)) {
0427   return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
0428 }
0429 
0430 // Apply the function to a tuple of arguments.
0431 template <typename F, typename Tuple>
0432 auto Apply(F&& f, Tuple&& args)
0433     -> decltype(ApplyImpl(
0434         std::forward<F>(f), std::forward<Tuple>(args),
0435         std::make_index_sequence<std::tuple_size<
0436             typename std::remove_reference<Tuple>::type>::value>())) {
0437   return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
0438                    std::make_index_sequence<std::tuple_size<
0439                        typename std::remove_reference<Tuple>::type>::value>());
0440 }
0441 
0442 // Template struct Function<F>, where F must be a function type, contains
0443 // the following typedefs:
0444 //
0445 //   Result:               the function's return type.
0446 //   Arg<N>:               the type of the N-th argument, where N starts with 0.
0447 //   ArgumentTuple:        the tuple type consisting of all parameters of F.
0448 //   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
0449 //                         parameters of F.
0450 //   MakeResultVoid:       the function type obtained by substituting void
0451 //                         for the return type of F.
0452 //   MakeResultIgnoredValue:
0453 //                         the function type obtained by substituting Something
0454 //                         for the return type of F.
0455 template <typename T>
0456 struct Function;
0457 
0458 template <typename R, typename... Args>
0459 struct Function<R(Args...)> {
0460   using Result = R;
0461   static constexpr size_t ArgumentCount = sizeof...(Args);
0462   template <size_t I>
0463   using Arg = ElemFromList<I, Args...>;
0464   using ArgumentTuple = std::tuple<Args...>;
0465   using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
0466   using MakeResultVoid = void(Args...);
0467   using MakeResultIgnoredValue = IgnoredValue(Args...);
0468 };
0469 
0470 // Workaround for MSVC error C2039: 'type': is not a member of 'std'
0471 // when std::tuple_element is used.
0472 // See: https://github.com/google/googletest/issues/3931
0473 // Can be replaced with std::tuple_element_t in C++14.
0474 template <size_t I, typename T>
0475 using TupleElement = typename std::tuple_element<I, T>::type;
0476 
0477 bool Base64Unescape(const std::string& encoded, std::string* decoded);
0478 
0479 GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4100 4805
0480 
0481 }  // namespace internal
0482 }  // namespace testing
0483 
0484 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_