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 GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40#define GMOCK_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
49namespace testing {
50
51template <typename>
52class Matcher;
53
54namespace 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.
66GTEST_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".
72GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
73
74// PointeeOf<Pointer>::type is the type of a value pointed to by a
75// Pointer, which can be either a smart pointer or a raw pointer. The
76// following default implementation is for the case where Pointer is a
77// smart pointer.
78template <typename Pointer>
79struct PointeeOf {
80 // Smart pointer classes define type element_type as the type of
81 // their pointees.
82 typedef typename Pointer::element_type type;
83};
84// This specialization is for the raw pointer case.
85template <typename T>
86struct PointeeOf<T*> { typedef T type; }; // NOLINT
87
88// GetRawPointer(p) returns the raw pointer underlying p when p is a
89// smart pointer, or returns p itself when p is already a raw pointer.
90// The following default implementation is for the smart pointer case.
91template <typename Pointer>
92inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
93 return p.get();
94}
95// This overloaded version is for the raw pointer case.
96template <typename Element>
97inline Element* GetRawPointer(Element* p) { return p; }
98
99// MSVC treats wchar_t as a native type usually, but treats it as the
100// same as unsigned short when the compiler option /Zc:wchar_t- is
101// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
102// is a native type.
103#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
104// wchar_t is a typedef.
105#else
106# define GMOCK_WCHAR_T_IS_NATIVE_ 1
107#endif
108
109// In what follows, we use the term "kind" to indicate whether a type
110// is bool, an integer type (excluding bool), a floating-point type,
111// or none of them. This categorization is useful for determining
112// when a matcher argument type can be safely converted to another
113// type in the implementation of SafeMatcherCast.
114enum TypeKind {
115 kBool, kInteger, kFloatingPoint, kOther
116};
117
118// KindOf<T>::value is the kind of type T.
119template <typename T> struct KindOf {
120 enum { value = kOther }; // The default kind.
121};
122
123// This macro declares that the kind of 'type' is 'kind'.
124#define GMOCK_DECLARE_KIND_(type, kind) \
125 template <> struct KindOf<type> { enum { value = kind }; }
126
127GMOCK_DECLARE_KIND_(bool, kBool);
128
129// All standard integer types.
130GMOCK_DECLARE_KIND_(char, kInteger);
131GMOCK_DECLARE_KIND_(signed char, kInteger);
132GMOCK_DECLARE_KIND_(unsigned char, kInteger);
133GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
134GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
135GMOCK_DECLARE_KIND_(int, kInteger);
136GMOCK_DECLARE_KIND_(unsigned int, kInteger);
137GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
138GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
139
140#if GMOCK_WCHAR_T_IS_NATIVE_
141GMOCK_DECLARE_KIND_(wchar_t, kInteger);
142#endif
143
144// Non-standard integer types.
145GMOCK_DECLARE_KIND_(Int64, kInteger);
146GMOCK_DECLARE_KIND_(UInt64, kInteger);
147
148// All standard floating-point types.
149GMOCK_DECLARE_KIND_(float, kFloatingPoint);
150GMOCK_DECLARE_KIND_(double, kFloatingPoint);
151GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
152
153#undef GMOCK_DECLARE_KIND_
154
155// Evaluates to the kind of 'type'.
156#define GMOCK_KIND_OF_(type) \
157 static_cast< ::testing::internal::TypeKind>( \
158 ::testing::internal::KindOf<type>::value)
159
160// Evaluates to true if integer type T is signed.
161#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
162
163// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
164// is true if arithmetic type From can be losslessly converted to
165// arithmetic type To.
166//
167// It's the user's responsibility to ensure that both From and To are
168// raw (i.e. has no CV modifier, is not a pointer, and is not a
169// reference) built-in arithmetic types, kFromKind is the kind of
170// From, and kToKind is the kind of To; the value is
171// implementation-defined when the above pre-condition is violated.
172template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
173struct LosslessArithmeticConvertibleImpl : public false_type {};
174
175// Converting bool to bool is lossless.
176template <>
177struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
178 : public true_type {}; // NOLINT
179
180// Converting bool to any integer type is lossless.
181template <typename To>
182struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
183 : public true_type {}; // NOLINT
184
185// Converting bool to any floating-point type is lossless.
186template <typename To>
187struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
188 : public true_type {}; // NOLINT
189
190// Converting an integer to bool is lossy.
191template <typename From>
192struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
193 : public false_type {}; // NOLINT
194
195// Converting an integer to another non-bool integer is lossless if
196// the target type's range encloses the source type's range.
197template <typename From, typename To>
198struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
199 : public bool_constant<
200 // When converting from a smaller size to a larger size, we are
201 // fine as long as we are not converting from signed to unsigned.
202 ((sizeof(From) < sizeof(To)) &&
203 (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
204 // When converting between the same size, the signedness must match.
205 ((sizeof(From) == sizeof(To)) &&
206 (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
207
208#undef GMOCK_IS_SIGNED_
209
210// Converting an integer to a floating-point type may be lossy, since
211// the format of a floating-point number is implementation-defined.
212template <typename From, typename To>
213struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
214 : public false_type {}; // NOLINT
215
216// Converting a floating-point to bool is lossy.
217template <typename From>
218struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
219 : public false_type {}; // NOLINT
220
221// Converting a floating-point to an integer is lossy.
222template <typename From, typename To>
223struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
224 : public false_type {}; // NOLINT
225
226// Converting a floating-point to another floating-point is lossless
227// if the target type is at least as big as the source type.
228template <typename From, typename To>
229struct LosslessArithmeticConvertibleImpl<
230 kFloatingPoint, From, kFloatingPoint, To>
231 : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
232
233// LosslessArithmeticConvertible<From, To>::value is true if arithmetic
234// type From can be losslessly converted to arithmetic type To.
235//
236// It's the user's responsibility to ensure that both From and To are
237// raw (i.e. has no CV modifier, is not a pointer, and is not a
238// reference) built-in arithmetic types; the value is
239// implementation-defined when the above pre-condition is violated.
240template <typename From, typename To>
241struct LosslessArithmeticConvertible
242 : public LosslessArithmeticConvertibleImpl<
243 GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
244
245// This interface knows how to report a Google Mock failure (either
246// non-fatal or fatal).
247class FailureReporterInterface {
248 public:
249 // The type of a failure (either non-fatal or fatal).
250 enum FailureType {
251 kNonfatal, kFatal
252 };
253
254 virtual ~FailureReporterInterface() {}
255
256 // Reports a failure that occurred at the given source file location.
257 virtual void ReportFailure(FailureType type, const char* file, int line,
258 const std::string& message) = 0;
259};
260
261// Returns the failure reporter used by Google Mock.
262GTEST_API_ FailureReporterInterface* GetFailureReporter();
263
264// Asserts that condition is true; aborts the process with the given
265// message if condition is false. We cannot use LOG(FATAL) or CHECK()
266// as Google Mock might be used to mock the log sink itself. We
267// inline this function to prevent it from showing up in the stack
268// trace.
269inline void Assert(bool condition, const char* file, int line,
270 const std::string& msg) {
271 if (!condition) {
272 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
273 file, line, msg);
274 }
275}
276inline void Assert(bool condition, const char* file, int line) {
277 Assert(condition, file, line, "Assertion failed.");
278}
279
280// Verifies that condition is true; generates a non-fatal failure if
281// condition is false.
282inline void Expect(bool condition, const char* file, int line,
283 const std::string& msg) {
284 if (!condition) {
285 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
286 file, line, msg);
287 }
288}
289inline void Expect(bool condition, const char* file, int line) {
290 Expect(condition, file, line, "Expectation failed.");
291}
292
293// Severity level of a log.
294enum LogSeverity {
295 kInfo = 0,
296 kWarning = 1
297};
298
299// Valid values for the --gmock_verbose flag.
300
301// All logs (informational and warnings) are printed.
302const char kInfoVerbosity[] = "info";
303// Only warnings are printed.
304const char kWarningVerbosity[] = "warning";
305// No logs are printed.
306const char kErrorVerbosity[] = "error";
307
308// Returns true if a log with the given severity is visible according
309// to the --gmock_verbose flag.
310GTEST_API_ bool LogIsVisible(LogSeverity severity);
311
312// Prints the given message to stdout if 'severity' >= the level
313// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
314// 0, also prints the stack trace excluding the top
315// stack_frames_to_skip frames. In opt mode, any positive
316// stack_frames_to_skip is treated as 0, since we don't know which
317// function calls will be inlined by the compiler and need to be
318// conservative.
319GTEST_API_ void Log(LogSeverity severity, const std::string& message,
320 int stack_frames_to_skip);
321
322// A marker class that is used to resolve parameterless expectations to the
323// correct overload. This must not be instantiable, to prevent client code from
324// accidentally resolving to the overload; for example:
325//
326// ON_CALL(mock, Method({}, nullptr))...
327//
328class WithoutMatchers {
329 private:
330 WithoutMatchers() {}
331 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
332};
333
334// Internal use only: access the singleton instance of WithoutMatchers.
335GTEST_API_ WithoutMatchers GetWithoutMatchers();
336
337// Type traits.
338
339// remove_reference<T>::type removes the reference from type T, if any.
340template <typename T> struct remove_reference { typedef T type; }; // NOLINT
341template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
342
343// DecayArray<T>::type turns an array type U[N] to const U* and preserves
344// other types. Useful for saving a copy of a function argument.
345template <typename T> struct DecayArray { typedef T type; }; // NOLINT
346template <typename T, size_t N> struct DecayArray<T[N]> {
347 typedef const T* type;
348};
349// Sometimes people use arrays whose size is not available at the use site
350// (e.g. extern const char kNamePrefix[]). This specialization covers that
351// case.
352template <typename T> struct DecayArray<T[]> {
353 typedef const T* type;
354};
355
356// Disable MSVC warnings for infinite recursion, since in this case the
357// the recursion is unreachable.
358#ifdef _MSC_VER
359# pragma warning(push)
360# pragma warning(disable:4717)
361#endif
362
363// Invalid<T>() is usable as an expression of type T, but will terminate
364// the program with an assertion failure if actually run. This is useful
365// when a value of type T is needed for compilation, but the statement
366// will not really be executed (or we don't care if the statement
367// crashes).
368template <typename T>
369inline T Invalid() {
370 Assert(false, "", -1, "Internal error: attempt to return invalid value");
371 // This statement is unreachable, and would never terminate even if it
372 // could be reached. It is provided only to placate compiler warnings
373 // about missing return statements.
374 return Invalid<T>();
375}
376
377#ifdef _MSC_VER
378# pragma warning(pop)
379#endif
380
381// Given a raw type (i.e. having no top-level reference or const
382// modifier) RawContainer that's either an STL-style container or a
383// native array, class StlContainerView<RawContainer> has the
384// following members:
385//
386// - type is a type that provides an STL-style container view to
387// (i.e. implements the STL container concept for) RawContainer;
388// - const_reference is a type that provides a reference to a const
389// RawContainer;
390// - ConstReference(raw_container) returns a const reference to an STL-style
391// container view to raw_container, which is a RawContainer.
392// - Copy(raw_container) returns an STL-style container view of a
393// copy of raw_container, which is a RawContainer.
394//
395// This generic version is used when RawContainer itself is already an
396// STL-style container.
397template <class RawContainer>
398class StlContainerView {
399 public:
400 typedef RawContainer type;
401 typedef const type& const_reference;
402
403 static const_reference ConstReference(const RawContainer& container) {
404 // Ensures that RawContainer is not a const type.
405 testing::StaticAssertTypeEq<
406 RawContainer, typename std::remove_const<RawContainer>::type>();
407 return container;
408 }
409 static type Copy(const RawContainer& container) { return container; }
410};
411
412// This specialization is used when RawContainer is a native array type.
413template <typename Element, size_t N>
414class StlContainerView<Element[N]> {
415 public:
416 typedef typename std::remove_const<Element>::type RawElement;
417 typedef internal::NativeArray<RawElement> type;
418 // NativeArray<T> can represent a native array either by value or by
419 // reference (selected by a constructor argument), so 'const type'
420 // can be used to reference a const native array. We cannot
421 // 'typedef const type& const_reference' here, as that would mean
422 // ConstReference() has to return a reference to a local variable.
423 typedef const type const_reference;
424
425 static const_reference ConstReference(const Element (&array)[N]) {
426 // Ensures that Element is not a const type.
427 testing::StaticAssertTypeEq<Element, RawElement>();
428 return type(array, N, RelationToSourceReference());
429 }
430 static type Copy(const Element (&array)[N]) {
431 return type(array, N, RelationToSourceCopy());
432 }
433};
434
435// This specialization is used when RawContainer is a native array
436// represented as a (pointer, size) tuple.
437template <typename ElementPointer, typename Size>
438class StlContainerView< ::std::tuple<ElementPointer, Size> > {
439 public:
440 typedef typename std::remove_const<
441 typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
442 typedef internal::NativeArray<RawElement> type;
443 typedef const type const_reference;
444
445 static const_reference ConstReference(
446 const ::std::tuple<ElementPointer, Size>& array) {
447 return type(std::get<0>(array), std::get<1>(array),
448 RelationToSourceReference());
449 }
450 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
451 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
452 }
453};
454
455// The following specialization prevents the user from instantiating
456// StlContainer with a reference type.
457template <typename T> class StlContainerView<T&>;
458
459// A type transform to remove constness from the first part of a pair.
460// Pairs like that are used as the value_type of associative containers,
461// and this transform produces a similar but assignable pair.
462template <typename T>
463struct RemoveConstFromKey {
464 typedef T type;
465};
466
467// Partially specialized to remove constness from std::pair<const K, V>.
468template <typename K, typename V>
469struct RemoveConstFromKey<std::pair<const K, V> > {
470 typedef std::pair<K, V> type;
471};
472
473// Mapping from booleans to types. Similar to boost::bool_<kValue> and
474// std::integral_constant<bool, kValue>.
475template <bool kValue>
476struct BooleanConstant {};
477
478// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
479// reduce code size.
480GTEST_API_ void IllegalDoDefault(const char* file, int line);
481
482// Helper types for Apply() below.
483template <size_t... Is> struct int_pack { typedef int_pack type; };
484
485template <class Pack, size_t I> struct append;
486template <size_t... Is, size_t I>
487struct append<int_pack<Is...>, I> : int_pack<Is..., I> {};
488
489template <size_t C>
490struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {};
491template <> struct make_int_pack<0> : int_pack<> {};
492
493template <typename F, typename Tuple, size_t... Idx>
494auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
495 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
496 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
497}
498
499// Apply the function to a tuple of arguments.
500template <typename F, typename Tuple>
501auto Apply(F&& f, Tuple&& args)
502 -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
503 make_int_pack<std::tuple_size<Tuple>::value>())) {
504 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
505 make_int_pack<std::tuple_size<Tuple>::value>());
506}
507
508// Template struct Function<F>, where F must be a function type, contains
509// the following typedefs:
510//
511// Result: the function's return type.
512// Arg<N>: the type of the N-th argument, where N starts with 0.
513// ArgumentTuple: the tuple type consisting of all parameters of F.
514// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
515// parameters of F.
516// MakeResultVoid: the function type obtained by substituting void
517// for the return type of F.
518// MakeResultIgnoredValue:
519// the function type obtained by substituting Something
520// for the return type of F.
521template <typename T>
522struct Function;
523
524template <typename R, typename... Args>
525struct Function<R(Args...)> {
526 using Result = R;
527 static constexpr size_t ArgumentCount = sizeof...(Args);
528 template <size_t I>
529 using Arg = ElemFromList<I, typename MakeIndexSequence<sizeof...(Args)>::type,
530 Args...>;
531 using ArgumentTuple = std::tuple<Args...>;
532 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
533 using MakeResultVoid = void(Args...);
534 using MakeResultIgnoredValue = IgnoredValue(Args...);
535};
536
537template <typename R, typename... Args>
538constexpr size_t Function<R(Args...)>::ArgumentCount;
539
540#ifdef _MSC_VER
541# pragma warning(pop)
542#endif
543
544} // namespace internal
545} // namespace testing
546
547#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
548