blob: 69a233804b552d5e1aab1f1fa723ff55bdb9508b [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file defines some utilities useful for implementing Google
35// Mock. They are subject to change without notice, so please DO NOT
36// USE THEM IN USER CODE.
37
38#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
39#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40
41#include <stdio.h>
42#include <ostream> // NOLINT
43#include <string>
44
45#include <gmock/internal/gmock-generated-internal-utils.h>
46#include <gmock/internal/gmock-port.h>
47#include <gtest/gtest.h>
48
49// Concatenates two pre-processor symbols; works for concatenating
50// built-in macros like __FILE__ and __LINE__.
zhanyong.wane0d051e2009-02-19 00:33:37 +000051#define GMOCK_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
52#define GMOCK_CONCAT_TOKEN_(foo, bar) GMOCK_CONCAT_TOKEN_IMPL_(foo, bar)
shiqiane35fdd92008-12-10 05:08:54 +000053
54#ifdef __GNUC__
zhanyong.wane0d051e2009-02-19 00:33:37 +000055#define GMOCK_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
shiqiane35fdd92008-12-10 05:08:54 +000056#else
zhanyong.wane0d051e2009-02-19 00:33:37 +000057#define GMOCK_ATTRIBUTE_UNUSED_
shiqiane35fdd92008-12-10 05:08:54 +000058#endif // __GNUC__
59
shiqiane35fdd92008-12-10 05:08:54 +000060namespace testing {
61namespace internal {
62
zhanyong.wance198ff2009-02-12 01:34:27 +000063// Converts an identifier name to a space-separated list of lower-case
64// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
65// treated as one word. For example, both "FooBar123" and
66// "foo_bar_123" are converted to "foo bar 123".
67string ConvertIdentifierNameToWords(const char* id_name);
68
shiqiane35fdd92008-12-10 05:08:54 +000069// PointeeOf<Pointer>::type is the type of a value pointed to by a
70// Pointer, which can be either a smart pointer or a raw pointer. The
71// following default implementation is for the case where Pointer is a
72// smart pointer.
73template <typename Pointer>
74struct PointeeOf {
75 // Smart pointer classes define type element_type as the type of
76 // their pointees.
77 typedef typename Pointer::element_type type;
78};
79// This specialization is for the raw pointer case.
80template <typename T>
81struct PointeeOf<T*> { typedef T type; }; // NOLINT
82
83// GetRawPointer(p) returns the raw pointer underlying p when p is a
84// smart pointer, or returns p itself when p is already a raw pointer.
85// The following default implementation is for the smart pointer case.
86template <typename Pointer>
87inline typename Pointer::element_type* GetRawPointer(const Pointer& p) {
88 return p.get();
89}
90// This overloaded version is for the raw pointer case.
91template <typename Element>
92inline Element* GetRawPointer(Element* p) { return p; }
93
94// This comparator allows linked_ptr to be stored in sets.
95template <typename T>
96struct LinkedPtrLessThan {
zhanyong.wan16cf4732009-05-14 20:55:30 +000097 bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
shiqiane35fdd92008-12-10 05:08:54 +000098 const ::testing::internal::linked_ptr<T>& rhs) const {
99 return lhs.get() < rhs.get();
100 }
101};
102
zhanyong.wan95b12332009-09-25 18:55:50 +0000103// Symbian compilation can be done with wchar_t being either a native
104// type or a typedef. Using Google Mock with OpenC without wchar_t
105// should require the definition of _STLP_NO_WCHAR_T.
106//
107// MSVC treats wchar_t as a native type usually, but treats it as the
108// same as unsigned short when the compiler option /Zc:wchar_t- is
109// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
110// is a native type.
111#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
112 (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
113// wchar_t is a typedef.
114#else
115#define GMOCK_WCHAR_T_IS_NATIVE_ 1
116#endif
117
118// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
119// Using them is a bad practice and not portable. So DON'T use them.
120//
121// Still, Google Mock is designed to work even if the user uses signed
122// wchar_t or unsigned wchar_t (obviously, assuming the compiler
123// supports them).
124//
125// To gcc,
126// wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
127#ifdef __GNUC__
128#define GMOCK_HAS_SIGNED_WCHAR_T_ 1 // signed/unsigned wchar_t are valid types.
129#endif
130
zhanyong.wan16cf4732009-05-14 20:55:30 +0000131// In what follows, we use the term "kind" to indicate whether a type
132// is bool, an integer type (excluding bool), a floating-point type,
133// or none of them. This categorization is useful for determining
134// when a matcher argument type can be safely converted to another
135// type in the implementation of SafeMatcherCast.
136enum TypeKind {
137 kBool, kInteger, kFloatingPoint, kOther
138};
139
140// KindOf<T>::value is the kind of type T.
141template <typename T> struct KindOf {
142 enum { value = kOther }; // The default kind.
143};
144
145// This macro declares that the kind of 'type' is 'kind'.
146#define GMOCK_DECLARE_KIND_(type, kind) \
147 template <> struct KindOf<type> { enum { value = kind }; }
148
149GMOCK_DECLARE_KIND_(bool, kBool);
150
151// All standard integer types.
152GMOCK_DECLARE_KIND_(char, kInteger);
153GMOCK_DECLARE_KIND_(signed char, kInteger);
154GMOCK_DECLARE_KIND_(unsigned char, kInteger);
155GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
156GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
157GMOCK_DECLARE_KIND_(int, kInteger);
158GMOCK_DECLARE_KIND_(unsigned int, kInteger);
159GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
160GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
161
zhanyong.wan95b12332009-09-25 18:55:50 +0000162#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wan16cf4732009-05-14 20:55:30 +0000163GMOCK_DECLARE_KIND_(wchar_t, kInteger);
164#endif
165
166// Non-standard integer types.
167GMOCK_DECLARE_KIND_(Int64, kInteger);
168GMOCK_DECLARE_KIND_(UInt64, kInteger);
169
170// All standard floating-point types.
171GMOCK_DECLARE_KIND_(float, kFloatingPoint);
172GMOCK_DECLARE_KIND_(double, kFloatingPoint);
173GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
174
175#undef GMOCK_DECLARE_KIND_
176
177// Evaluates to the kind of 'type'.
178#define GMOCK_KIND_OF_(type) \
179 static_cast< ::testing::internal::TypeKind>( \
180 ::testing::internal::KindOf<type>::value)
181
182// Evaluates to true iff integer type T is signed.
183#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
184
185// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
186// is true iff arithmetic type From can be losslessly converted to
187// arithmetic type To.
188//
189// It's the user's responsibility to ensure that both From and To are
190// raw (i.e. has no CV modifier, is not a pointer, and is not a
191// reference) built-in arithmetic types, kFromKind is the kind of
192// From, and kToKind is the kind of To; the value is
193// implementation-defined when the above pre-condition is violated.
194template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
195struct LosslessArithmeticConvertibleImpl : public false_type {};
196
197// Converting bool to bool is lossless.
198template <>
199struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
200 : public true_type {}; // NOLINT
201
202// Converting bool to any integer type is lossless.
203template <typename To>
204struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
205 : public true_type {}; // NOLINT
206
207// Converting bool to any floating-point type is lossless.
208template <typename To>
209struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
210 : public true_type {}; // NOLINT
211
212// Converting an integer to bool is lossy.
213template <typename From>
214struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
215 : public false_type {}; // NOLINT
216
217// Converting an integer to another non-bool integer is lossless iff
218// the target type's range encloses the source type's range.
219template <typename From, typename To>
220struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
221 : public bool_constant<
222 // When converting from a smaller size to a larger size, we are
223 // fine as long as we are not converting from signed to unsigned.
224 ((sizeof(From) < sizeof(To)) &&
225 (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
226 // When converting between the same size, the signedness must match.
227 ((sizeof(From) == sizeof(To)) &&
228 (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
229
230#undef GMOCK_IS_SIGNED_
231
232// Converting an integer to a floating-point type may be lossy, since
233// the format of a floating-point number is implementation-defined.
234template <typename From, typename To>
235struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
236 : public false_type {}; // NOLINT
237
238// Converting a floating-point to bool is lossy.
239template <typename From>
240struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
241 : public false_type {}; // NOLINT
242
243// Converting a floating-point to an integer is lossy.
244template <typename From, typename To>
245struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
246 : public false_type {}; // NOLINT
247
248// Converting a floating-point to another floating-point is lossless
249// iff the target type is at least as big as the source type.
250template <typename From, typename To>
251struct LosslessArithmeticConvertibleImpl<
252 kFloatingPoint, From, kFloatingPoint, To>
253 : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
254
255// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
256// type From can be losslessly converted to arithmetic type To.
257//
258// It's the user's responsibility to ensure that both From and To are
259// raw (i.e. has no CV modifier, is not a pointer, and is not a
260// reference) built-in arithmetic types; the value is
261// implementation-defined when the above pre-condition is violated.
262template <typename From, typename To>
263struct LosslessArithmeticConvertible
264 : public LosslessArithmeticConvertibleImpl<
265 GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT
266
shiqiane35fdd92008-12-10 05:08:54 +0000267// This interface knows how to report a Google Mock failure (either
268// non-fatal or fatal).
269class FailureReporterInterface {
270 public:
271 // The type of a failure (either non-fatal or fatal).
272 enum FailureType {
273 NONFATAL, FATAL
274 };
275
276 virtual ~FailureReporterInterface() {}
277
278 // Reports a failure that occurred at the given source file location.
279 virtual void ReportFailure(FailureType type, const char* file, int line,
280 const string& message) = 0;
281};
282
283// Returns the failure reporter used by Google Mock.
284FailureReporterInterface* GetFailureReporter();
285
286// Asserts that condition is true; aborts the process with the given
287// message if condition is false. We cannot use LOG(FATAL) or CHECK()
288// as Google Mock might be used to mock the log sink itself. We
289// inline this function to prevent it from showing up in the stack
290// trace.
291inline void Assert(bool condition, const char* file, int line,
292 const string& msg) {
293 if (!condition) {
294 GetFailureReporter()->ReportFailure(FailureReporterInterface::FATAL,
295 file, line, msg);
296 }
297}
298inline void Assert(bool condition, const char* file, int line) {
299 Assert(condition, file, line, "Assertion failed.");
300}
301
302// Verifies that condition is true; generates a non-fatal failure if
303// condition is false.
304inline void Expect(bool condition, const char* file, int line,
305 const string& msg) {
306 if (!condition) {
307 GetFailureReporter()->ReportFailure(FailureReporterInterface::NONFATAL,
308 file, line, msg);
309 }
310}
311inline void Expect(bool condition, const char* file, int line) {
312 Expect(condition, file, line, "Expectation failed.");
313}
314
315// Severity level of a log.
316enum LogSeverity {
317 INFO = 0,
318 WARNING = 1,
319};
320
321// Valid values for the --gmock_verbose flag.
322
323// All logs (informational and warnings) are printed.
324const char kInfoVerbosity[] = "info";
325// Only warnings are printed.
326const char kWarningVerbosity[] = "warning";
327// No logs are printed.
328const char kErrorVerbosity[] = "error";
329
zhanyong.wan9413f2f2009-05-29 19:50:06 +0000330// Returns true iff a log with the given severity is visible according
331// to the --gmock_verbose flag.
332bool LogIsVisible(LogSeverity severity);
333
shiqiane35fdd92008-12-10 05:08:54 +0000334// Prints the given message to stdout iff 'severity' >= the level
335// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
336// 0, also prints the stack trace excluding the top
337// stack_frames_to_skip frames. In opt mode, any positive
338// stack_frames_to_skip is treated as 0, since we don't know which
339// function calls will be inlined by the compiler and need to be
340// conservative.
341void Log(LogSeverity severity, const string& message, int stack_frames_to_skip);
342
zhanyong.wan16cf4732009-05-14 20:55:30 +0000343// TODO(wan@google.com): group all type utilities together.
344
shiqiane35fdd92008-12-10 05:08:54 +0000345// Type traits.
346
347// is_reference<T>::value is non-zero iff T is a reference type.
348template <typename T> struct is_reference : public false_type {};
349template <typename T> struct is_reference<T&> : public true_type {};
350
351// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
352template <typename T1, typename T2> struct type_equals : public false_type {};
353template <typename T> struct type_equals<T, T> : public true_type {};
354
355// remove_reference<T>::type removes the reference from type T, if any.
zhanyong.wan16cf4732009-05-14 20:55:30 +0000356template <typename T> struct remove_reference { typedef T type; }; // NOLINT
357template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000358
359// Invalid<T>() returns an invalid value of type T. This is useful
360// when a value of type T is needed for compilation, but the statement
361// will not really be executed (or we don't care if the statement
362// crashes).
363template <typename T>
364inline T Invalid() {
365 return *static_cast<typename remove_reference<T>::type*>(NULL);
366}
367template <>
368inline void Invalid<void>() {}
369
zhanyong.wanb8243162009-06-04 05:48:20 +0000370// Given a raw type (i.e. having no top-level reference or const
371// modifier) RawContainer that's either an STL-style container or a
372// native array, class StlContainerView<RawContainer> has the
373// following members:
374//
375// - type is a type that provides an STL-style container view to
376// (i.e. implements the STL container concept for) RawContainer;
377// - const_reference is a type that provides a reference to a const
378// RawContainer;
379// - ConstReference(raw_container) returns a const reference to an STL-style
380// container view to raw_container, which is a RawContainer.
381// - Copy(raw_container) returns an STL-style container view of a
382// copy of raw_container, which is a RawContainer.
383//
384// This generic version is used when RawContainer itself is already an
385// STL-style container.
386template <class RawContainer>
387class StlContainerView {
388 public:
389 typedef RawContainer type;
390 typedef const type& const_reference;
391
392 static const_reference ConstReference(const RawContainer& container) {
393 // Ensures that RawContainer is not a const type.
394 testing::StaticAssertTypeEq<RawContainer,
zhanyong.wan02f71062010-05-10 17:14:29 +0000395 GTEST_REMOVE_CONST_(RawContainer)>();
zhanyong.wanb8243162009-06-04 05:48:20 +0000396 return container;
397 }
398 static type Copy(const RawContainer& container) { return container; }
399};
400
401// This specialization is used when RawContainer is a native array type.
402template <typename Element, size_t N>
403class StlContainerView<Element[N]> {
404 public:
zhanyong.wan02f71062010-05-10 17:14:29 +0000405 typedef GTEST_REMOVE_CONST_(Element) RawElement;
zhanyong.wanb8243162009-06-04 05:48:20 +0000406 typedef internal::NativeArray<RawElement> type;
407 // NativeArray<T> can represent a native array either by value or by
408 // reference (selected by a constructor argument), so 'const type'
409 // can be used to reference a const native array. We cannot
410 // 'typedef const type& const_reference' here, as that would mean
411 // ConstReference() has to return a reference to a local variable.
412 typedef const type const_reference;
413
414 static const_reference ConstReference(const Element (&array)[N]) {
415 // Ensures that Element is not a const type.
416 testing::StaticAssertTypeEq<Element, RawElement>();
zhanyong.wan95b12332009-09-25 18:55:50 +0000417#if GTEST_OS_SYMBIAN
418 // The Nokia Symbian compiler confuses itself in template instantiation
419 // for this call without the cast to Element*:
420 // function call '[testing::internal::NativeArray<char *>].NativeArray(
421 // {lval} const char *[4], long, testing::internal::RelationToSource)'
422 // does not match
423 // 'testing::internal::NativeArray<char *>::NativeArray(
424 // char *const *, unsigned int, testing::internal::RelationToSource)'
425 // (instantiating: 'testing::internal::ContainsMatcherImpl
426 // <const char * (&)[4]>::Matches(const char * (&)[4]) const')
427 // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
428 // ConstReference(const char * (&)[4])')
429 // (and though the N parameter type is mismatched in the above explicit
430 // conversion of it doesn't help - only the conversion of the array).
431 return type(const_cast<Element*>(&array[0]), N, kReference);
432#else
zhanyong.wan4bd79e42009-09-16 17:38:08 +0000433 return type(array, N, kReference);
zhanyong.wan95b12332009-09-25 18:55:50 +0000434#endif // GTEST_OS_SYMBIAN
zhanyong.wanb8243162009-06-04 05:48:20 +0000435 }
436 static type Copy(const Element (&array)[N]) {
zhanyong.wan95b12332009-09-25 18:55:50 +0000437#if GTEST_OS_SYMBIAN
438 return type(const_cast<Element*>(&array[0]), N, kCopy);
439#else
zhanyong.wan4bd79e42009-09-16 17:38:08 +0000440 return type(array, N, kCopy);
zhanyong.wan95b12332009-09-25 18:55:50 +0000441#endif // GTEST_OS_SYMBIAN
zhanyong.wanb8243162009-06-04 05:48:20 +0000442 }
443};
444
445// This specialization is used when RawContainer is a native array
446// represented as a (pointer, size) tuple.
447template <typename ElementPointer, typename Size>
448class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > {
449 public:
zhanyong.wan02f71062010-05-10 17:14:29 +0000450 typedef GTEST_REMOVE_CONST_(
zhanyong.wanb8243162009-06-04 05:48:20 +0000451 typename internal::PointeeOf<ElementPointer>::type) RawElement;
452 typedef internal::NativeArray<RawElement> type;
453 typedef const type const_reference;
454
455 static const_reference ConstReference(
456 const ::std::tr1::tuple<ElementPointer, Size>& array) {
zhanyong.wan4bd79e42009-09-16 17:38:08 +0000457 using ::std::tr1::get;
458 return type(get<0>(array), get<1>(array), kReference);
zhanyong.wanb8243162009-06-04 05:48:20 +0000459 }
460 static type Copy(const ::std::tr1::tuple<ElementPointer, Size>& array) {
zhanyong.wan4bd79e42009-09-16 17:38:08 +0000461 using ::std::tr1::get;
462 return type(get<0>(array), get<1>(array), kCopy);
zhanyong.wanb8243162009-06-04 05:48:20 +0000463 }
464};
465
466// The following specialization prevents the user from instantiating
467// StlContainer with a reference type.
468template <typename T> class StlContainerView<T&>;
469
shiqiane35fdd92008-12-10 05:08:54 +0000470} // namespace internal
471} // namespace testing
472
473#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_