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