Coverage Report

Created: 2020-06-26 05:44

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