]> git.proxmox.com Git - ceph.git/blame - ceph/src/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h
import 15.2.0 Octopus source
[ceph.git] / ceph / src / googletest / googlemock / include / gmock / internal / gmock-internal-utils.h
CommitLineData
7c673cae
FG
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.
9f95a23c 29
7c673cae
FG
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
9f95a23c
TL
37// GOOGLETEST_CM0002 DO NOT DELETE
38
7c673cae
FG
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>
9f95a23c 45#include <type_traits>
7c673cae
FG
46#include "gmock/internal/gmock-port.h"
47#include "gtest/gtest.h"
48
49namespace testing {
9f95a23c
TL
50
51template <typename>
52class Matcher;
53
7c673cae
FG
54namespace internal {
55
9f95a23c
TL
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
7c673cae
FG
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".
9f95a23c 72GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
7c673cae
FG
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
7c673cae
FG
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.
9f95a23c 103#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
7c673cae
FG
104// wchar_t is a typedef.
105#else
106# define GMOCK_WCHAR_T_IS_NATIVE_ 1
107#endif
108
7c673cae
FG
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
9f95a23c
TL
139GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
140GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
7c673cae
FG
141
142#if GMOCK_WCHAR_T_IS_NATIVE_
143GMOCK_DECLARE_KIND_(wchar_t, kInteger);
144#endif
145
7c673cae
FG
146// All standard floating-point types.
147GMOCK_DECLARE_KIND_(float, kFloatingPoint);
148GMOCK_DECLARE_KIND_(double, kFloatingPoint);
149GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
150
151#undef GMOCK_DECLARE_KIND_
152
153// Evaluates to the kind of 'type'.
154#define GMOCK_KIND_OF_(type) \
155 static_cast< ::testing::internal::TypeKind>( \
156 ::testing::internal::KindOf<type>::value)
157
7c673cae 158// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
9f95a23c 159// is true if and only if arithmetic type From can be losslessly converted to
7c673cae
FG
160// arithmetic type To.
161//
162// It's the user's responsibility to ensure that both From and To are
163// raw (i.e. has no CV modifier, is not a pointer, and is not a
164// reference) built-in arithmetic types, kFromKind is the kind of
165// From, and kToKind is the kind of To; the value is
166// implementation-defined when the above pre-condition is violated.
167template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
9f95a23c
TL
168using LosslessArithmeticConvertibleImpl = std::integral_constant<
169 bool,
170 // clang-format off
171 // Converting from bool is always lossless
172 (kFromKind == kBool) ? true
173 // Converting between any other type kinds will be lossy if the type
174 // kinds are not the same.
175 : (kFromKind != kToKind) ? false
176 : (kFromKind == kInteger &&
177 // Converting between integers of different widths is allowed so long
178 // as the conversion does not go from signed to unsigned.
179 (((sizeof(From) < sizeof(To)) &&
180 !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
181 // Converting between integers of the same width only requires the
182 // two types to have the same signedness.
183 ((sizeof(From) == sizeof(To)) &&
184 (std::is_signed<From>::value == std::is_signed<To>::value)))
185 ) ? true
186 // Floating point conversions are lossless if and only if `To` is at least
187 // as wide as `From`.
188 : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
189 : false
190 // clang-format on
191 >;
192
193// LosslessArithmeticConvertible<From, To>::value is true if and only if
194// arithmetic type From can be losslessly converted to arithmetic type To.
7c673cae
FG
195//
196// It's the user's responsibility to ensure that both From and To are
197// raw (i.e. has no CV modifier, is not a pointer, and is not a
198// reference) built-in arithmetic types; the value is
199// implementation-defined when the above pre-condition is violated.
200template <typename From, typename To>
9f95a23c
TL
201using LosslessArithmeticConvertible =
202 LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
203 GMOCK_KIND_OF_(To), To>;
7c673cae
FG
204
205// This interface knows how to report a Google Mock failure (either
206// non-fatal or fatal).
207class FailureReporterInterface {
208 public:
209 // The type of a failure (either non-fatal or fatal).
210 enum FailureType {
211 kNonfatal, kFatal
212 };
213
214 virtual ~FailureReporterInterface() {}
215
216 // Reports a failure that occurred at the given source file location.
217 virtual void ReportFailure(FailureType type, const char* file, int line,
9f95a23c 218 const std::string& message) = 0;
7c673cae
FG
219};
220
221// Returns the failure reporter used by Google Mock.
222GTEST_API_ FailureReporterInterface* GetFailureReporter();
223
224// Asserts that condition is true; aborts the process with the given
225// message if condition is false. We cannot use LOG(FATAL) or CHECK()
226// as Google Mock might be used to mock the log sink itself. We
227// inline this function to prevent it from showing up in the stack
228// trace.
229inline void Assert(bool condition, const char* file, int line,
9f95a23c 230 const std::string& msg) {
7c673cae
FG
231 if (!condition) {
232 GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
233 file, line, msg);
234 }
235}
236inline void Assert(bool condition, const char* file, int line) {
237 Assert(condition, file, line, "Assertion failed.");
238}
239
240// Verifies that condition is true; generates a non-fatal failure if
241// condition is false.
242inline void Expect(bool condition, const char* file, int line,
9f95a23c 243 const std::string& msg) {
7c673cae
FG
244 if (!condition) {
245 GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
246 file, line, msg);
247 }
248}
249inline void Expect(bool condition, const char* file, int line) {
250 Expect(condition, file, line, "Expectation failed.");
251}
252
253// Severity level of a log.
254enum LogSeverity {
255 kInfo = 0,
256 kWarning = 1
257};
258
259// Valid values for the --gmock_verbose flag.
260
261// All logs (informational and warnings) are printed.
262const char kInfoVerbosity[] = "info";
263// Only warnings are printed.
264const char kWarningVerbosity[] = "warning";
265// No logs are printed.
266const char kErrorVerbosity[] = "error";
267
9f95a23c
TL
268// Returns true if and only if a log with the given severity is visible
269// according to the --gmock_verbose flag.
7c673cae
FG
270GTEST_API_ bool LogIsVisible(LogSeverity severity);
271
9f95a23c 272// Prints the given message to stdout if and only if 'severity' >= the level
7c673cae
FG
273// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
274// 0, also prints the stack trace excluding the top
275// stack_frames_to_skip frames. In opt mode, any positive
276// stack_frames_to_skip is treated as 0, since we don't know which
277// function calls will be inlined by the compiler and need to be
278// conservative.
9f95a23c 279GTEST_API_ void Log(LogSeverity severity, const std::string& message,
7c673cae
FG
280 int stack_frames_to_skip);
281
9f95a23c
TL
282// A marker class that is used to resolve parameterless expectations to the
283// correct overload. This must not be instantiable, to prevent client code from
284// accidentally resolving to the overload; for example:
285//
286// ON_CALL(mock, Method({}, nullptr))...
287//
288class WithoutMatchers {
289 private:
290 WithoutMatchers() {}
291 friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
7c673cae
FG
292};
293
9f95a23c
TL
294// Internal use only: access the singleton instance of WithoutMatchers.
295GTEST_API_ WithoutMatchers GetWithoutMatchers();
296
7c673cae
FG
297// Disable MSVC warnings for infinite recursion, since in this case the
298// the recursion is unreachable.
299#ifdef _MSC_VER
300# pragma warning(push)
301# pragma warning(disable:4717)
302#endif
303
304// Invalid<T>() is usable as an expression of type T, but will terminate
305// the program with an assertion failure if actually run. This is useful
306// when a value of type T is needed for compilation, but the statement
307// will not really be executed (or we don't care if the statement
308// crashes).
309template <typename T>
310inline T Invalid() {
311 Assert(false, "", -1, "Internal error: attempt to return invalid value");
312 // This statement is unreachable, and would never terminate even if it
313 // could be reached. It is provided only to placate compiler warnings
314 // about missing return statements.
315 return Invalid<T>();
316}
317
318#ifdef _MSC_VER
319# pragma warning(pop)
320#endif
321
322// Given a raw type (i.e. having no top-level reference or const
323// modifier) RawContainer that's either an STL-style container or a
324// native array, class StlContainerView<RawContainer> has the
325// following members:
326//
327// - type is a type that provides an STL-style container view to
328// (i.e. implements the STL container concept for) RawContainer;
329// - const_reference is a type that provides a reference to a const
330// RawContainer;
331// - ConstReference(raw_container) returns a const reference to an STL-style
332// container view to raw_container, which is a RawContainer.
333// - Copy(raw_container) returns an STL-style container view of a
334// copy of raw_container, which is a RawContainer.
335//
336// This generic version is used when RawContainer itself is already an
337// STL-style container.
338template <class RawContainer>
339class StlContainerView {
340 public:
341 typedef RawContainer type;
342 typedef const type& const_reference;
343
344 static const_reference ConstReference(const RawContainer& container) {
9f95a23c
TL
345 static_assert(!std::is_const<RawContainer>::value,
346 "RawContainer type must not be const");
7c673cae
FG
347 return container;
348 }
349 static type Copy(const RawContainer& container) { return container; }
350};
351
352// This specialization is used when RawContainer is a native array type.
353template <typename Element, size_t N>
354class StlContainerView<Element[N]> {
355 public:
9f95a23c 356 typedef typename std::remove_const<Element>::type RawElement;
7c673cae
FG
357 typedef internal::NativeArray<RawElement> type;
358 // NativeArray<T> can represent a native array either by value or by
359 // reference (selected by a constructor argument), so 'const type'
360 // can be used to reference a const native array. We cannot
361 // 'typedef const type& const_reference' here, as that would mean
362 // ConstReference() has to return a reference to a local variable.
363 typedef const type const_reference;
364
365 static const_reference ConstReference(const Element (&array)[N]) {
9f95a23c
TL
366 static_assert(std::is_same<Element, RawElement>::value,
367 "Element type must not be const");
7c673cae 368 return type(array, N, RelationToSourceReference());
7c673cae
FG
369 }
370 static type Copy(const Element (&array)[N]) {
7c673cae 371 return type(array, N, RelationToSourceCopy());
7c673cae
FG
372 }
373};
374
375// This specialization is used when RawContainer is a native array
376// represented as a (pointer, size) tuple.
377template <typename ElementPointer, typename Size>
9f95a23c 378class StlContainerView< ::std::tuple<ElementPointer, Size> > {
7c673cae 379 public:
9f95a23c
TL
380 typedef typename std::remove_const<
381 typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
7c673cae
FG
382 typedef internal::NativeArray<RawElement> type;
383 typedef const type const_reference;
384
385 static const_reference ConstReference(
9f95a23c
TL
386 const ::std::tuple<ElementPointer, Size>& array) {
387 return type(std::get<0>(array), std::get<1>(array),
388 RelationToSourceReference());
7c673cae 389 }
9f95a23c
TL
390 static type Copy(const ::std::tuple<ElementPointer, Size>& array) {
391 return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());
7c673cae
FG
392 }
393};
394
395// The following specialization prevents the user from instantiating
396// StlContainer with a reference type.
397template <typename T> class StlContainerView<T&>;
398
399// A type transform to remove constness from the first part of a pair.
400// Pairs like that are used as the value_type of associative containers,
401// and this transform produces a similar but assignable pair.
402template <typename T>
403struct RemoveConstFromKey {
404 typedef T type;
405};
406
407// Partially specialized to remove constness from std::pair<const K, V>.
408template <typename K, typename V>
409struct RemoveConstFromKey<std::pair<const K, V> > {
410 typedef std::pair<K, V> type;
411};
412
9f95a23c
TL
413// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
414// reduce code size.
415GTEST_API_ void IllegalDoDefault(const char* file, int line);
416
417template <typename F, typename Tuple, size_t... Idx>
418auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
419 std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
420 return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
421}
422
423// Apply the function to a tuple of arguments.
424template <typename F, typename Tuple>
425auto Apply(F&& f, Tuple&& args)
426 -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
427 MakeIndexSequence<std::tuple_size<Tuple>::value>())) {
428 return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
429 MakeIndexSequence<std::tuple_size<Tuple>::value>());
430}
431
432// Template struct Function<F>, where F must be a function type, contains
433// the following typedefs:
434//
435// Result: the function's return type.
436// Arg<N>: the type of the N-th argument, where N starts with 0.
437// ArgumentTuple: the tuple type consisting of all parameters of F.
438// ArgumentMatcherTuple: the tuple type consisting of Matchers for all
439// parameters of F.
440// MakeResultVoid: the function type obtained by substituting void
441// for the return type of F.
442// MakeResultIgnoredValue:
443// the function type obtained by substituting Something
444// for the return type of F.
445template <typename T>
446struct Function;
447
448template <typename R, typename... Args>
449struct Function<R(Args...)> {
450 using Result = R;
451 static constexpr size_t ArgumentCount = sizeof...(Args);
452 template <size_t I>
453 using Arg = ElemFromList<I, Args...>;
454 using ArgumentTuple = std::tuple<Args...>;
455 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
456 using MakeResultVoid = void(Args...);
457 using MakeResultIgnoredValue = IgnoredValue(Args...);
458};
459
460template <typename R, typename... Args>
461constexpr size_t Function<R(Args...)>::ArgumentCount;
462
463#ifdef _MSC_VER
464# pragma warning(pop)
465#endif
7c673cae
FG
466
467} // namespace internal
468} // namespace testing
469
470#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_