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