blob: b3d1a1d10f12d0bd79d189b1f416380db468da23 [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
60class ProtocolMessage;
61namespace proto2 { class Message; }
62
63namespace testing {
64namespace internal {
65
zhanyong.wance198ff2009-02-12 01:34:27 +000066// Converts an identifier name to a space-separated list of lower-case
67// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
68// treated as one word. For example, both "FooBar123" and
69// "foo_bar_123" are converted to "foo bar 123".
70string ConvertIdentifierNameToWords(const char* id_name);
71
shiqiane35fdd92008-12-10 05:08:54 +000072// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
73// compiler error iff T1 and T2 are different types.
74template <typename T1, typename T2>
75struct CompileAssertTypesEqual;
76
77template <typename T>
78struct CompileAssertTypesEqual<T, T> {
79};
80
81// Removes the reference from a type if it is a reference type,
82// otherwise leaves it unchanged. This is the same as
83// tr1::remove_reference, which is not widely available yet.
84template <typename T>
85struct RemoveReference { typedef T type; }; // NOLINT
86template <typename T>
87struct RemoveReference<T&> { typedef T type; }; // NOLINT
88
89// A handy wrapper around RemoveReference that works when the argument
90// T depends on template parameters.
zhanyong.wane0d051e2009-02-19 00:33:37 +000091#define GMOCK_REMOVE_REFERENCE_(T) \
shiqiane35fdd92008-12-10 05:08:54 +000092 typename ::testing::internal::RemoveReference<T>::type
93
94// Removes const from a type if it is a const type, otherwise leaves
95// it unchanged. This is the same as tr1::remove_const, which is not
96// widely available yet.
97template <typename T>
98struct RemoveConst { typedef T type; }; // NOLINT
99template <typename T>
100struct RemoveConst<const T> { typedef T type; }; // NOLINT
101
102// A handy wrapper around RemoveConst that works when the argument
103// T depends on template parameters.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000104#define GMOCK_REMOVE_CONST_(T) \
shiqiane35fdd92008-12-10 05:08:54 +0000105 typename ::testing::internal::RemoveConst<T>::type
106
107// Adds reference to a type if it is not a reference type,
108// otherwise leaves it unchanged. This is the same as
109// tr1::add_reference, which is not widely available yet.
110template <typename T>
111struct AddReference { typedef T& type; }; // NOLINT
112template <typename T>
113struct AddReference<T&> { typedef T& type; }; // NOLINT
114
115// A handy wrapper around AddReference that works when the argument T
116// depends on template parameters.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000117#define GMOCK_ADD_REFERENCE_(T) \
shiqiane35fdd92008-12-10 05:08:54 +0000118 typename ::testing::internal::AddReference<T>::type
119
120// Adds a reference to const on top of T as necessary. For example,
121// it transforms
122//
123// char ==> const char&
124// const char ==> const char&
125// char& ==> const char&
126// const char& ==> const char&
127//
128// The argument T must depend on some template parameters.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000129#define GMOCK_REFERENCE_TO_CONST_(T) \
130 GMOCK_ADD_REFERENCE_(const GMOCK_REMOVE_REFERENCE_(T))
shiqiane35fdd92008-12-10 05:08:54 +0000131
132// PointeeOf<Pointer>::type is the type of a value pointed to by a
133// Pointer, which can be either a smart pointer or a raw pointer. The
134// following default implementation is for the case where Pointer is a
135// smart pointer.
136template <typename Pointer>
137struct PointeeOf {
138 // Smart pointer classes define type element_type as the type of
139 // their pointees.
140 typedef typename Pointer::element_type type;
141};
142// This specialization is for the raw pointer case.
143template <typename T>
144struct PointeeOf<T*> { typedef T type; }; // NOLINT
145
146// GetRawPointer(p) returns the raw pointer underlying p when p is a
147// smart pointer, or returns p itself when p is already a raw pointer.
148// The following default implementation is for the smart pointer case.
149template <typename Pointer>
150inline typename Pointer::element_type* GetRawPointer(const Pointer& p) {
151 return p.get();
152}
153// This overloaded version is for the raw pointer case.
154template <typename Element>
155inline Element* GetRawPointer(Element* p) { return p; }
156
157// This comparator allows linked_ptr to be stored in sets.
158template <typename T>
159struct LinkedPtrLessThan {
160 bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
161 const ::testing::internal::linked_ptr<T>& rhs) const {
162 return lhs.get() < rhs.get();
163 }
164};
165
166// ImplicitlyConvertible<From, To>::value is a compile-time bool
167// constant that's true iff type From can be implicitly converted to
168// type To.
169template <typename From, typename To>
170class ImplicitlyConvertible {
171 private:
172 // We need the following helper functions only for their types.
173 // They have no implementations.
174
175 // MakeFrom() is an expression whose type is From. We cannot simply
176 // use From(), as the type From may not have a public default
177 // constructor.
178 static From MakeFrom();
179
180 // These two functions are overloaded. Given an expression
181 // Helper(x), the compiler will pick the first version if x can be
182 // implicitly converted to type To; otherwise it will pick the
183 // second version.
184 //
185 // The first version returns a value of size 1, and the second
186 // version returns a value of size 2. Therefore, by checking the
187 // size of Helper(x), which can be done at compile time, we can tell
188 // which version of Helper() is used, and hence whether x can be
189 // implicitly converted to type To.
190 static char Helper(To);
191 static char (&Helper(...))[2]; // NOLINT
192
193 // We have to put the 'public' section after the 'private' section,
194 // or MSVC refuses to compile the code.
195 public:
196 // MSVC warns about implicitly converting from double to int for
197 // possible loss of data, so we need to temporarily disable the
198 // warning.
199#ifdef _MSC_VER
200#pragma warning(push) // Saves the current warning state.
201#pragma warning(disable:4244) // Temporarily disables warning 4244.
202 static const bool value =
203 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
204#pragma warning(pop) // Restores the warning state.
205#else
206 static const bool value =
207 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
208#endif // _MSV_VER
209};
210template <typename From, typename To>
211const bool ImplicitlyConvertible<From, To>::value;
212
213// IsAProtocolMessage<T>::value is a compile-time bool constant that's
214// true iff T is type ProtocolMessage, proto2::Message, or a subclass
215// of those.
216template <typename T>
217struct IsAProtocolMessage {
218 static const bool value =
219 ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
220 ImplicitlyConvertible<const T*, const ::proto2::Message*>::value;
221};
222template <typename T>
223const bool IsAProtocolMessage<T>::value;
224
225// When the compiler sees expression IsContainerTest<C>(0), the first
226// overload of IsContainerTest will be picked if C is an STL-style
227// container class (since C::const_iterator* is a valid type and 0 can
228// be converted to it), while the second overload will be picked
229// otherwise (since C::const_iterator will be an invalid type in this
230// case). Therefore, we can determine whether C is a container class
231// by checking the type of IsContainerTest<C>(0). The value of the
232// expression is insignificant.
233typedef int IsContainer;
234template <class C>
235IsContainer IsContainerTest(typename C::const_iterator*) { return 0; }
236
237typedef char IsNotContainer;
238template <class C>
239IsNotContainer IsContainerTest(...) { return '\0'; }
240
241// This interface knows how to report a Google Mock failure (either
242// non-fatal or fatal).
243class FailureReporterInterface {
244 public:
245 // The type of a failure (either non-fatal or fatal).
246 enum FailureType {
247 NONFATAL, FATAL
248 };
249
250 virtual ~FailureReporterInterface() {}
251
252 // Reports a failure that occurred at the given source file location.
253 virtual void ReportFailure(FailureType type, const char* file, int line,
254 const string& message) = 0;
255};
256
257// Returns the failure reporter used by Google Mock.
258FailureReporterInterface* GetFailureReporter();
259
260// Asserts that condition is true; aborts the process with the given
261// message if condition is false. We cannot use LOG(FATAL) or CHECK()
262// as Google Mock might be used to mock the log sink itself. We
263// inline this function to prevent it from showing up in the stack
264// trace.
265inline void Assert(bool condition, const char* file, int line,
266 const string& msg) {
267 if (!condition) {
268 GetFailureReporter()->ReportFailure(FailureReporterInterface::FATAL,
269 file, line, msg);
270 }
271}
272inline void Assert(bool condition, const char* file, int line) {
273 Assert(condition, file, line, "Assertion failed.");
274}
275
276// Verifies that condition is true; generates a non-fatal failure if
277// condition is false.
278inline void Expect(bool condition, const char* file, int line,
279 const string& msg) {
280 if (!condition) {
281 GetFailureReporter()->ReportFailure(FailureReporterInterface::NONFATAL,
282 file, line, msg);
283 }
284}
285inline void Expect(bool condition, const char* file, int line) {
286 Expect(condition, file, line, "Expectation failed.");
287}
288
289// Severity level of a log.
290enum LogSeverity {
291 INFO = 0,
292 WARNING = 1,
293};
294
295// Valid values for the --gmock_verbose flag.
296
297// All logs (informational and warnings) are printed.
298const char kInfoVerbosity[] = "info";
299// Only warnings are printed.
300const char kWarningVerbosity[] = "warning";
301// No logs are printed.
302const char kErrorVerbosity[] = "error";
303
304// Prints the given message to stdout iff 'severity' >= the level
305// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
306// 0, also prints the stack trace excluding the top
307// stack_frames_to_skip frames. In opt mode, any positive
308// stack_frames_to_skip is treated as 0, since we don't know which
309// function calls will be inlined by the compiler and need to be
310// conservative.
311void Log(LogSeverity severity, const string& message, int stack_frames_to_skip);
312
313// The universal value printer (public/gmock-printers.h) needs this
314// to declare an unused << operator in the global namespace.
315struct Unused {};
316
317// Type traits.
318
319// is_reference<T>::value is non-zero iff T is a reference type.
320template <typename T> struct is_reference : public false_type {};
321template <typename T> struct is_reference<T&> : public true_type {};
322
323// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
324template <typename T1, typename T2> struct type_equals : public false_type {};
325template <typename T> struct type_equals<T, T> : public true_type {};
326
327// remove_reference<T>::type removes the reference from type T, if any.
328template <typename T> struct remove_reference { typedef T type; };
329template <typename T> struct remove_reference<T&> { typedef T type; };
330
331// Invalid<T>() returns an invalid value of type T. This is useful
332// when a value of type T is needed for compilation, but the statement
333// will not really be executed (or we don't care if the statement
334// crashes).
335template <typename T>
336inline T Invalid() {
337 return *static_cast<typename remove_reference<T>::type*>(NULL);
338}
339template <>
340inline void Invalid<void>() {}
341
342} // namespace internal
343} // namespace testing
344
345#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_