Debian Codegraph @

llvm-project/third-party/unittest/googlemock/include/gmock/internal/gmock-internal-utils.h

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