1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Google Mock - a framework for writing C++ mock classes.
32 // This file defines some utilities useful for implementing Google
33 // Mock. They are subject to change without notice, so please DO NOT
34 // USE THEM IN USER CODE.
36 // IWYU pragma: private, include "gmock/gmock.h"
37 // IWYU pragma: friend gmock/.*
39 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
44 #include <ostream> // NOLINT
46 #include <type_traits>
49 #include "gmock/internal/gmock-port.h"
50 #include "gtest/gtest.h"
59 // Silence MSVC C4100 (unreferenced formal parameter) and
60 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
63 #pragma warning(disable : 4100)
64 #pragma warning(disable : 4805)
67 // Joins a vector of strings as if they are fields of a tuple; returns
69 GTEST_API_ std::string JoinAsKeyValueTuple(
70 const std::vector<const char*>& names, const Strings& values);
72 // Converts an identifier name to a space-separated list of lower-case
73 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
74 // treated as one word. For example, both "FooBar123" and
75 // "foo_bar_123" are converted to "foo bar 123".
76 GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
78 // GetRawPointer(p) returns the raw pointer underlying p when p is a
79 // smart pointer, or returns p itself when p is already a raw pointer.
80 // The following default implementation is for the smart pointer case.
81 template <typename Pointer>
82 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
85 // This overload version is for std::reference_wrapper, which does not work with
86 // the overload above, as it does not have an `element_type`.
87 template <typename Element>
88 inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
92 // This overloaded version is for the raw pointer case.
93 template <typename Element>
94 inline Element* GetRawPointer(Element* p) {
98 // MSVC treats wchar_t as a native type usually, but treats it as the
99 // same as unsigned short when the compiler option /Zc:wchar_t- is
100 // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
102 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
103 // wchar_t is a typedef.
105 #define GMOCK_WCHAR_T_IS_NATIVE_ 1
108 // In what follows, we use the term "kind" to indicate whether a type
109 // is bool, an integer type (excluding bool), a floating-point type,
110 // or none of them. This categorization is useful for determining
111 // when a matcher argument type can be safely converted to another
112 // type in the implementation of SafeMatcherCast.
113 enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
115 // KindOf<T>::value is the kind of type T.
116 template <typename T>
118 enum { value = kOther }; // The default kind.
121 // This macro declares that the kind of 'type' is 'kind'.
122 #define GMOCK_DECLARE_KIND_(type, kind) \
124 struct KindOf<type> { \
125 enum { value = kind }; \
128 GMOCK_DECLARE_KIND_(bool, kBool);
130 // All standard integer types.
131 GMOCK_DECLARE_KIND_(char, kInteger);
132 GMOCK_DECLARE_KIND_(signed char, kInteger);
133 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
134 GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
135 GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
136 GMOCK_DECLARE_KIND_(int, kInteger);
137 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
138 GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
139 GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
140 GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
141 GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
143 #if GMOCK_WCHAR_T_IS_NATIVE_
144 GMOCK_DECLARE_KIND_(wchar_t, kInteger);
147 // All standard floating-point types.
148 GMOCK_DECLARE_KIND_(float, kFloatingPoint);
149 GMOCK_DECLARE_KIND_(double, kFloatingPoint);
150 GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
152 #undef GMOCK_DECLARE_KIND_
154 // Evaluates to the kind of 'type'.
155 #define GMOCK_KIND_OF_(type) \
156 static_cast< ::testing::internal::TypeKind>( \
157 ::testing::internal::KindOf<type>::value)
159 // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
160 // is true if and only if arithmetic type From can be losslessly converted to
161 // arithmetic type To.
163 // It's the user's responsibility to ensure that both From and To are
164 // raw (i.e. has no CV modifier, is not a pointer, and is not a
165 // reference) built-in arithmetic types, kFromKind is the kind of
166 // From, and kToKind is the kind of To; the value is
167 // implementation-defined when the above pre-condition is violated.
168 template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
169 using LosslessArithmeticConvertibleImpl = std::integral_constant<
172 // Converting from bool is always lossless
173 (kFromKind == kBool) ? true
174 // Converting between any other type kinds will be lossy if the type
175 // kinds are not the same.
176 : (kFromKind != kToKind) ? false
177 : (kFromKind == kInteger &&
178 // Converting between integers of different widths is allowed so long
179 // as the conversion does not go from signed to unsigned.
180 (((sizeof(From) < sizeof(To)) &&
181 !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
182 // Converting between integers of the same width only requires the
183 // two types to have the same signedness.
184 ((sizeof(From) == sizeof(To)) &&
185 (std::is_signed<From>::value == std::is_signed<To>::value)))
187 // Floating point conversions are lossless if and only if `To` is at least
188 // as wide as `From`.
189 : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
194 // LosslessArithmeticConvertible<From, To>::value is true if and only if
195 // arithmetic type From can be losslessly converted to arithmetic type To.
197 // It's the user's responsibility to ensure that both From and To are
198 // raw (i.e. has no CV modifier, is not a pointer, and is not a
199 // reference) built-in arithmetic types; the value is
200 // implementation-defined when the above pre-condition is violated.
201 template <typename From, typename To>
202 using LosslessArithmeticConvertible =
203 LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
204 GMOCK_KIND_OF_(To), To>;
206 // This interface knows how to report a Google Mock failure (either
207 // non-fatal or fatal).
208 class FailureReporterInterface {
210 // The type of a failure (either non-fatal or fatal).
211 enum FailureType { kNonfatal, kFatal };
213 virtual ~FailureReporterInterface() {}
215 // Reports a failure that occurred at the given source file location.
216 virtual void ReportFailure(FailureType type, const char* file, int line,
217 const std::string& message) = 0;
220 // Returns the failure reporter used by Google Mock.
221 GTEST_API_ FailureReporterInterface* GetFailureReporter();
223 // Asserts that condition is true; aborts the process with the given
224 // message if condition is false. We cannot use LOG(FATAL) or CHECK()
225 // as Google Mock might be used to mock the log sink itself. We
226 // inline this function to prevent it from showing up in the stack
228 inline void Assert(bool condition, const char* file, int line,
229 const std::string& msg) {
231 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
235 inline void Assert(bool condition, const char* file, int line) {
236 Assert(condition, file, line, "Assertion failed.");
239 // Verifies that condition is true; generates a non-fatal failure if
240 // condition is false.
241 inline void Expect(bool condition, const char* file, int line,
242 const std::string& msg) {
244 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
248 inline void Expect(bool condition, const char* file, int line) {
249 Expect(condition, file, line, "Expectation failed.");
252 // Severity level of a log.
253 enum LogSeverity { kInfo = 0, kWarning = 1 };
255 // Valid values for the --gmock_verbose flag.
257 // All logs (informational and warnings) are printed.
258 const char kInfoVerbosity[] = "info";
259 // Only warnings are printed.
260 const char kWarningVerbosity[] = "warning";
261 // No logs are printed.
262 const char kErrorVerbosity[] = "error";
264 // Returns true if and only if a log with the given severity is visible
265 // according to the --gmock_verbose flag.
266 GTEST_API_ bool LogIsVisible(LogSeverity severity);
268 // Prints the given message to stdout if and only if 'severity' >= the level
269 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
270 // 0, also prints the stack trace excluding the top
271 // stack_frames_to_skip frames. In opt mode, any positive
272 // stack_frames_to_skip is treated as 0, since we don't know which
273 // function calls will be inlined by the compiler and need to be
275 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
276 int stack_frames_to_skip);
278 // A marker class that is used to resolve parameterless expectations to the
279 // correct overload. This must not be instantiable, to prevent client code from
280 // accidentally resolving to the overload; for example:
282 // ON_CALL(mock, Method({}, nullptr))...
284 class WithoutMatchers {
287 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
290 // Internal use only: access the singleton instance of WithoutMatchers.
291 GTEST_API_ WithoutMatchers GetWithoutMatchers();
293 // Disable MSVC warnings for infinite recursion, since in this case the
294 // recursion is unreachable.
296 #pragma warning(push)
297 #pragma warning(disable : 4717)
300 // Invalid<T>() is usable as an expression of type T, but will terminate
301 // the program with an assertion failure if actually run. This is useful
302 // when a value of type T is needed for compilation, but the statement
303 // will not really be executed (or we don't care if the statement
305 template <typename T>
307 Assert(false, "", -1, "Internal error: attempt to return invalid value");
308 #if defined(__GNUC__) || defined(__clang__)
309 __builtin_unreachable();
310 #elif defined(_MSC_VER)
321 // Given a raw type (i.e. having no top-level reference or const
322 // modifier) RawContainer that's either an STL-style container or a
323 // native array, class StlContainerView<RawContainer> has the
324 // following members:
326 // - type is a type that provides an STL-style container view to
327 // (i.e. implements the STL container concept for) RawContainer;
328 // - const_reference is a type that provides a reference to a const
330 // - ConstReference(raw_container) returns a const reference to an STL-style
331 // container view to raw_container, which is a RawContainer.
332 // - Copy(raw_container) returns an STL-style container view of a
333 // copy of raw_container, which is a RawContainer.
335 // This generic version is used when RawContainer itself is already an
336 // STL-style container.
337 template <class RawContainer>
338 class StlContainerView {
340 typedef RawContainer type;
341 typedef const type& const_reference;
343 static const_reference ConstReference(const RawContainer& container) {
344 static_assert(!std::is_const<RawContainer>::value,
345 "RawContainer type must not be const");
348 static type Copy(const RawContainer& container) { return container; }
351 // This specialization is used when RawContainer is a native array type.
352 template <typename Element, size_t N>
353 class StlContainerView<Element[N]> {
355 typedef typename std::remove_const<Element>::type RawElement;
356 typedef internal::NativeArray<RawElement> type;
357 // NativeArray<T> can represent a native array either by value or by
358 // reference (selected by a constructor argument), so 'const type'
359 // can be used to reference a const native array. We cannot
360 // 'typedef const type& const_reference' here, as that would mean
361 // ConstReference() has to return a reference to a local variable.
362 typedef const type const_reference;
364 static const_reference ConstReference(const Element (&array)[N]) {
365 static_assert(std::is_same<Element, RawElement>::value,
366 "Element type must not be const");
367 return type(array, N, RelationToSourceReference());
369 static type Copy(const Element (&array)[N]) {
370 return type(array, N, RelationToSourceCopy());
374 // This specialization is used when RawContainer is a native array
375 // represented as a (pointer, size) tuple.
376 template <typename ElementPointer, typename Size>
377 class StlContainerView< ::std::tuple<ElementPointer, Size> > {
379 typedef typename std::remove_const<
380 typename std::pointer_traits<ElementPointer>::element_type>::type
382 typedef internal::NativeArray<RawElement> type;
383 typedef const type const_reference;
385 static const_reference ConstReference(
386 const ::std::tuple<ElementPointer, Size>& array) {
387 return type(std::get<0>(array), std::get<1>(array),
388 RelationToSourceReference());
390 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
391 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
395 // The following specialization prevents the user from instantiating
396 // StlContainer with a reference type.
397 template <typename T>
398 class StlContainerView<T&>;
400 // A type transform to remove constness from the first part of a pair.
401 // Pairs like that are used as the value_type of associative containers,
402 // and this transform produces a similar but assignable pair.
403 template <typename T>
404 struct RemoveConstFromKey {
408 // Partially specialized to remove constness from std::pair<const K, V>.
409 template <typename K, typename V>
410 struct RemoveConstFromKey<std::pair<const K, V> > {
411 typedef std::pair<K, V> type;
414 // Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
416 GTEST_API_ void IllegalDoDefault(const char* file, int line);
418 template <typename F, typename Tuple, size_t... Idx>
419 auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
420 -> decltype(std::forward<F>(f)(
421 std::get<Idx>(std::forward<Tuple>(args))...)) {
422 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
425 // Apply the function to a tuple of arguments.
426 template <typename F, typename Tuple>
427 auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
428 std::forward<F>(f), std::forward<Tuple>(args),
429 MakeIndexSequence<std::tuple_size<
430 typename std::remove_reference<Tuple>::type>::value>())) {
431 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
432 MakeIndexSequence<std::tuple_size<
433 typename std::remove_reference<Tuple>::type>::value>());
436 // Template struct Function<F>, where F must be a function type, contains
437 // the following typedefs:
439 // Result: the function's return type.
440 // Arg<N>: the type of the N-th argument, where N starts with 0.
441 // ArgumentTuple: the tuple type consisting of all parameters of F.
442 // ArgumentMatcherTuple: the tuple type consisting of Matchers for all
444 // MakeResultVoid: the function type obtained by substituting void
445 // for the return type of F.
446 // MakeResultIgnoredValue:
447 // the function type obtained by substituting Something
448 // for the return type of F.
449 template <typename T>
452 template <typename R, typename... Args>
453 struct Function<R(Args...)> {
455 static constexpr size_t ArgumentCount = sizeof...(Args);
457 using Arg = ElemFromList<I, Args...>;
458 using ArgumentTuple = std::tuple<Args...>;
459 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
460 using MakeResultVoid = void(Args...);
461 using MakeResultIgnoredValue = IgnoredValue(Args...);
464 template <typename R, typename... Args>
465 constexpr size_t Function<R(Args...)>::ArgumentCount;
467 bool Base64Unescape(const std::string& encoded, std::string* decoded);
473 } // namespace internal
474 } // namespace testing
476 #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_