Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-02-22 10:39:26

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 <vector>
0048 
0049 #include "gmock/internal/gmock-port.h"
0050 #include "gtest/gtest.h"
0051 
0052 namespace testing {
0053 
0054 template <typename>
0055 class Matcher;
0056 
0057 namespace internal {
0058 
0059 // Silence MSVC C4100 (unreferenced formal parameter) and
0060 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
0061 #ifdef _MSC_VER
0062 #pragma warning(push)
0063 #pragma warning(disable : 4100)
0064 #pragma warning(disable : 4805)
0065 #endif
0066 
0067 // Joins a vector of strings as if they are fields of a tuple; returns
0068 // the joined string.
0069 GTEST_API_ std::string JoinAsKeyValueTuple(
0070     const std::vector<const char*>& names, const Strings& values);
0071 
0072 // Converts an identifier name to a space-separated list of lower-case
0073 // words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
0074 // treated as one word.  For example, both "FooBar123" and
0075 // "foo_bar_123" are converted to "foo bar 123".
0076 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
0077 
0078 // GetRawPointer(p) returns the raw pointer underlying p when p is a
0079 // smart pointer, or returns p itself when p is already a raw pointer.
0080 // The following default implementation is for the smart pointer case.
0081 template <typename Pointer>
0082 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
0083   return p.get();
0084 }
0085 // This overload version is for std::reference_wrapper, which does not work with
0086 // the overload above, as it does not have an `element_type`.
0087 template <typename Element>
0088 inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
0089   return &r.get();
0090 }
0091 
0092 // This overloaded version is for the raw pointer case.
0093 template <typename Element>
0094 inline Element* GetRawPointer(Element* p) {
0095   return p;
0096 }
0097 
0098 // MSVC treats wchar_t as a native type usually, but treats it as the
0099 // same as unsigned short when the compiler option /Zc:wchar_t- is
0100 // specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
0101 // is a native type.
0102 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
0103 // wchar_t is a typedef.
0104 #else
0105 #define GMOCK_WCHAR_T_IS_NATIVE_ 1
0106 #endif
0107 
0108 // In what follows, we use the term "kind" to indicate whether a type
0109 // is bool, an integer type (excluding bool), a floating-point type,
0110 // or none of them.  This categorization is useful for determining
0111 // when a matcher argument type can be safely converted to another
0112 // type in the implementation of SafeMatcherCast.
0113 enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
0114 
0115 // KindOf<T>::value is the kind of type T.
0116 template <typename T>
0117 struct KindOf {
0118   enum { value = kOther };  // The default kind.
0119 };
0120 
0121 // This macro declares that the kind of 'type' is 'kind'.
0122 #define GMOCK_DECLARE_KIND_(type, kind) \
0123   template <>                           \
0124   struct KindOf<type> {                 \
0125     enum { value = kind };              \
0126   }
0127 
0128 GMOCK_DECLARE_KIND_(bool, kBool);
0129 
0130 // All standard integer types.
0131 GMOCK_DECLARE_KIND_(char, kInteger);
0132 GMOCK_DECLARE_KIND_(signed char, kInteger);
0133 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
0134 GMOCK_DECLARE_KIND_(short, kInteger);           // NOLINT
0135 GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
0136 GMOCK_DECLARE_KIND_(int, kInteger);
0137 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
0138 GMOCK_DECLARE_KIND_(long, kInteger);                // NOLINT
0139 GMOCK_DECLARE_KIND_(unsigned long, kInteger);       // NOLINT
0140 GMOCK_DECLARE_KIND_(long long, kInteger);           // NOLINT
0141 GMOCK_DECLARE_KIND_(unsigned long long, kInteger);  // NOLINT
0142 
0143 #if GMOCK_WCHAR_T_IS_NATIVE_
0144 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
0145 #endif
0146 
0147 // All standard floating-point types.
0148 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
0149 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
0150 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
0151 
0152 #undef GMOCK_DECLARE_KIND_
0153 
0154 // Evaluates to the kind of 'type'.
0155 #define GMOCK_KIND_OF_(type)                   \
0156   static_cast< ::testing::internal::TypeKind>( \
0157       ::testing::internal::KindOf<type>::value)
0158 
0159 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
0160 // is true if and only if arithmetic type From can be losslessly converted to
0161 // arithmetic type To.
0162 //
0163 // It's the user's responsibility to ensure that both From and To are
0164 // raw (i.e. has no CV modifier, is not a pointer, and is not a
0165 // reference) built-in arithmetic types, kFromKind is the kind of
0166 // From, and kToKind is the kind of To; the value is
0167 // implementation-defined when the above pre-condition is violated.
0168 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
0169 using LosslessArithmeticConvertibleImpl = std::integral_constant<
0170     bool,
0171     // clang-format off
0172       // Converting from bool is always lossless
0173       (kFromKind == kBool) ? true
0174       // Converting between any other type kinds will be lossy if the type
0175       // kinds are not the same.
0176     : (kFromKind != kToKind) ? false
0177     : (kFromKind == kInteger &&
0178        // Converting between integers of different widths is allowed so long
0179        // as the conversion does not go from signed to unsigned.
0180       (((sizeof(From) < sizeof(To)) &&
0181         !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
0182        // Converting between integers of the same width only requires the
0183        // two types to have the same signedness.
0184        ((sizeof(From) == sizeof(To)) &&
0185         (std::is_signed<From>::value == std::is_signed<To>::value)))
0186        ) ? true
0187       // Floating point conversions are lossless if and only if `To` is at least
0188       // as wide as `From`.
0189     : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
0190     : false
0191     // clang-format on
0192     >;
0193 
0194 // LosslessArithmeticConvertible<From, To>::value is true if and only if
0195 // arithmetic type From can be losslessly converted to arithmetic type To.
0196 //
0197 // It's the user's responsibility to ensure that both From and To are
0198 // raw (i.e. has no CV modifier, is not a pointer, and is not a
0199 // reference) built-in arithmetic types; the value is
0200 // implementation-defined when the above pre-condition is violated.
0201 template <typename From, typename To>
0202 using LosslessArithmeticConvertible =
0203     LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
0204                                       GMOCK_KIND_OF_(To), To>;
0205 
0206 // This interface knows how to report a Google Mock failure (either
0207 // non-fatal or fatal).
0208 class FailureReporterInterface {
0209  public:
0210   // The type of a failure (either non-fatal or fatal).
0211   enum FailureType { kNonfatal, kFatal };
0212 
0213   virtual ~FailureReporterInterface() {}
0214 
0215   // Reports a failure that occurred at the given source file location.
0216   virtual void ReportFailure(FailureType type, const char* file, int line,
0217                              const std::string& message) = 0;
0218 };
0219 
0220 // Returns the failure reporter used by Google Mock.
0221 GTEST_API_ FailureReporterInterface* GetFailureReporter();
0222 
0223 // Asserts that condition is true; aborts the process with the given
0224 // message if condition is false.  We cannot use LOG(FATAL) or CHECK()
0225 // as Google Mock might be used to mock the log sink itself.  We
0226 // inline this function to prevent it from showing up in the stack
0227 // trace.
0228 inline void Assert(bool condition, const char* file, int line,
0229                    const std::string& msg) {
0230   if (!condition) {
0231     GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
0232                                         line, msg);
0233   }
0234 }
0235 inline void Assert(bool condition, const char* file, int line) {
0236   Assert(condition, file, line, "Assertion failed.");
0237 }
0238 
0239 // Verifies that condition is true; generates a non-fatal failure if
0240 // condition is false.
0241 inline void Expect(bool condition, const char* file, int line,
0242                    const std::string& msg) {
0243   if (!condition) {
0244     GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
0245                                         file, line, msg);
0246   }
0247 }
0248 inline void Expect(bool condition, const char* file, int line) {
0249   Expect(condition, file, line, "Expectation failed.");
0250 }
0251 
0252 // Severity level of a log.
0253 enum LogSeverity { kInfo = 0, kWarning = 1 };
0254 
0255 // Valid values for the --gmock_verbose flag.
0256 
0257 // All logs (informational and warnings) are printed.
0258 const char kInfoVerbosity[] = "info";
0259 // Only warnings are printed.
0260 const char kWarningVerbosity[] = "warning";
0261 // No logs are printed.
0262 const char kErrorVerbosity[] = "error";
0263 
0264 // Returns true if and only if a log with the given severity is visible
0265 // according to the --gmock_verbose flag.
0266 GTEST_API_ bool LogIsVisible(LogSeverity severity);
0267 
0268 // Prints the given message to stdout if and only if 'severity' >= the level
0269 // specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
0270 // 0, also prints the stack trace excluding the top
0271 // stack_frames_to_skip frames.  In opt mode, any positive
0272 // stack_frames_to_skip is treated as 0, since we don't know which
0273 // function calls will be inlined by the compiler and need to be
0274 // conservative.
0275 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
0276                     int stack_frames_to_skip);
0277 
0278 // A marker class that is used to resolve parameterless expectations to the
0279 // correct overload. This must not be instantiable, to prevent client code from
0280 // accidentally resolving to the overload; for example:
0281 //
0282 //    ON_CALL(mock, Method({}, nullptr))...
0283 //
0284 class WithoutMatchers {
0285  private:
0286   WithoutMatchers() {}
0287   friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
0288 };
0289 
0290 // Internal use only: access the singleton instance of WithoutMatchers.
0291 GTEST_API_ WithoutMatchers GetWithoutMatchers();
0292 
0293 // Disable MSVC warnings for infinite recursion, since in this case the
0294 // recursion is unreachable.
0295 #ifdef _MSC_VER
0296 #pragma warning(push)
0297 #pragma warning(disable : 4717)
0298 #endif
0299 
0300 // Invalid<T>() is usable as an expression of type T, but will terminate
0301 // the program with an assertion failure if actually run.  This is useful
0302 // when a value of type T is needed for compilation, but the statement
0303 // will not really be executed (or we don't care if the statement
0304 // crashes).
0305 template <typename T>
0306 inline T Invalid() {
0307   Assert(false, "", -1, "Internal error: attempt to return invalid value");
0308 #if defined(__GNUC__) || defined(__clang__)
0309   __builtin_unreachable();
0310 #elif defined(_MSC_VER)
0311   __assume(0);
0312 #else
0313   return Invalid<T>();
0314 #endif
0315 }
0316 
0317 #ifdef _MSC_VER
0318 #pragma warning(pop)
0319 #endif
0320 
0321 // Given a raw type (i.e. having no top-level reference or const
0322 // modifier) RawContainer that's either an STL-style container or a
0323 // native array, class StlContainerView<RawContainer> has the
0324 // following members:
0325 //
0326 //   - type is a type that provides an STL-style container view to
0327 //     (i.e. implements the STL container concept for) RawContainer;
0328 //   - const_reference is a type that provides a reference to a const
0329 //     RawContainer;
0330 //   - ConstReference(raw_container) returns a const reference to an STL-style
0331 //     container view to raw_container, which is a RawContainer.
0332 //   - Copy(raw_container) returns an STL-style container view of a
0333 //     copy of raw_container, which is a RawContainer.
0334 //
0335 // This generic version is used when RawContainer itself is already an
0336 // STL-style container.
0337 template <class RawContainer>
0338 class StlContainerView {
0339  public:
0340   typedef RawContainer type;
0341   typedef const type& const_reference;
0342 
0343   static const_reference ConstReference(const RawContainer& container) {
0344     static_assert(!std::is_const<RawContainer>::value,
0345                   "RawContainer type must not be const");
0346     return container;
0347   }
0348   static type Copy(const RawContainer& container) { return container; }
0349 };
0350 
0351 // This specialization is used when RawContainer is a native array type.
0352 template <typename Element, size_t N>
0353 class StlContainerView<Element[N]> {
0354  public:
0355   typedef typename std::remove_const<Element>::type RawElement;
0356   typedef internal::NativeArray<RawElement> type;
0357   // NativeArray<T> can represent a native array either by value or by
0358   // reference (selected by a constructor argument), so 'const type'
0359   // can be used to reference a const native array.  We cannot
0360   // 'typedef const type& const_reference' here, as that would mean
0361   // ConstReference() has to return a reference to a local variable.
0362   typedef const type const_reference;
0363 
0364   static const_reference ConstReference(const Element (&array)[N]) {
0365     static_assert(std::is_same<Element, RawElement>::value,
0366                   "Element type must not be const");
0367     return type(array, N, RelationToSourceReference());
0368   }
0369   static type Copy(const Element (&array)[N]) {
0370     return type(array, N, RelationToSourceCopy());
0371   }
0372 };
0373 
0374 // This specialization is used when RawContainer is a native array
0375 // represented as a (pointer, size) tuple.
0376 template <typename ElementPointer, typename Size>
0377 class StlContainerView< ::std::tuple<ElementPointer, Size> > {
0378  public:
0379   typedef typename std::remove_const<
0380       typename std::pointer_traits<ElementPointer>::element_type>::type
0381       RawElement;
0382   typedef internal::NativeArray<RawElement> type;
0383   typedef const type const_reference;
0384 
0385   static const_reference ConstReference(
0386       const ::std::tuple<ElementPointer, Size>& array) {
0387     return type(std::get<0>(array), std::get<1>(array),
0388                 RelationToSourceReference());
0389   }
0390   static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
0391     return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
0392   }
0393 };
0394 
0395 // The following specialization prevents the user from instantiating
0396 // StlContainer with a reference type.
0397 template <typename T>
0398 class StlContainerView<T&>;
0399 
0400 // A type transform to remove constness from the first part of a pair.
0401 // Pairs like that are used as the value_type of associative containers,
0402 // and this transform produces a similar but assignable pair.
0403 template <typename T>
0404 struct RemoveConstFromKey {
0405   typedef T type;
0406 };
0407 
0408 // Partially specialized to remove constness from std::pair<const K, V>.
0409 template <typename K, typename V>
0410 struct RemoveConstFromKey<std::pair<const K, V> > {
0411   typedef std::pair<K, V> type;
0412 };
0413 
0414 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
0415 // reduce code size.
0416 GTEST_API_ void IllegalDoDefault(const char* file, int line);
0417 
0418 template <typename F, typename Tuple, size_t... Idx>
0419 auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
0420     -> decltype(std::forward<F>(f)(
0421         std::get<Idx>(std::forward<Tuple>(args))...)) {
0422   return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
0423 }
0424 
0425 // Apply the function to a tuple of arguments.
0426 template <typename F, typename Tuple>
0427 auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
0428     std::forward<F>(f), std::forward<Tuple>(args),
0429     MakeIndexSequence<std::tuple_size<
0430         typename std::remove_reference<Tuple>::type>::value>())) {
0431   return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
0432                    MakeIndexSequence<std::tuple_size<
0433                        typename std::remove_reference<Tuple>::type>::value>());
0434 }
0435 
0436 // Template struct Function<F>, where F must be a function type, contains
0437 // the following typedefs:
0438 //
0439 //   Result:               the function's return type.
0440 //   Arg<N>:               the type of the N-th argument, where N starts with 0.
0441 //   ArgumentTuple:        the tuple type consisting of all parameters of F.
0442 //   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
0443 //                         parameters of F.
0444 //   MakeResultVoid:       the function type obtained by substituting void
0445 //                         for the return type of F.
0446 //   MakeResultIgnoredValue:
0447 //                         the function type obtained by substituting Something
0448 //                         for the return type of F.
0449 template <typename T>
0450 struct Function;
0451 
0452 template <typename R, typename... Args>
0453 struct Function<R(Args...)> {
0454   using Result = R;
0455   static constexpr size_t ArgumentCount = sizeof...(Args);
0456   template <size_t I>
0457   using Arg = ElemFromList<I, Args...>;
0458   using ArgumentTuple = std::tuple<Args...>;
0459   using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
0460   using MakeResultVoid = void(Args...);
0461   using MakeResultIgnoredValue = IgnoredValue(Args...);
0462 };
0463 
0464 template <typename R, typename... Args>
0465 constexpr size_t Function<R(Args...)>::ArgumentCount;
0466 
0467 bool Base64Unescape(const std::string& encoded, std::string* decoded);
0468 
0469 #ifdef _MSC_VER
0470 #pragma warning(pop)
0471 #endif
0472 
0473 }  // namespace internal
0474 }  // namespace testing
0475 
0476 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_