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