1 // Copyright 2005, 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 // The Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // This header file declares functions and macros used internally by
33 // Google Test.  They are subject to change without notice.
34 
35 // GOOGLETEST_CM0001 DO NOT DELETE
36 
37 // IWYU pragma: private, include "gtest/gtest.h"
38 // IWYU pragma: friend gtest/.*
39 // IWYU pragma: friend gmock/.*
40 
41 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
42 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
43 
44 #include "gtest/internal/gtest-port.h"
45 
46 #if GTEST_OS_LINUX
47 # include <stdlib.h>
48 # include <sys/types.h>
49 # include <sys/wait.h>
50 # include <unistd.h>
51 #endif  // GTEST_OS_LINUX
52 
53 #if GTEST_HAS_EXCEPTIONS
54 # include <stdexcept>
55 #endif
56 
57 #include <ctype.h>
58 #include <float.h>
59 #include <string.h>
60 #include <iomanip>
61 #include <limits>
62 #include <map>
63 #include <set>
64 #include <string>
65 #include <type_traits>
66 #include <vector>
67 
68 #include "gtest/gtest-message.h"
69 #include "gtest/internal/gtest-filepath.h"
70 #include "gtest/internal/gtest-string.h"
71 #include "gtest/internal/gtest-type-util.h"
72 
73 // Due to C++ preprocessor weirdness, we need double indirection to
74 // concatenate two tokens when one of them is __LINE__.  Writing
75 //
76 //   foo ## __LINE__
77 //
78 // will result in the token foo__LINE__, instead of foo followed by
79 // the current line number.  For more details, see
80 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
81 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
82 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
83 
84 // Stringifies its argument.
85 #define GTEST_STRINGIFY_(name) #name
86 
87 namespace proto2 { class Message; }
88 
89 namespace testing {
90 
91 // Forward declarations.
92 
93 class AssertionResult;                 // Result of an assertion.
94 class Message;                         // Represents a failure message.
95 class Test;                            // Represents a test.
96 class TestInfo;                        // Information about a test.
97 class TestPartResult;                  // Result of a test part.
98 class UnitTest;                        // A collection of test suites.
99 
100 template <typename T>
101 ::std::string PrintToString(const T& value);
102 
103 namespace internal {
104 
105 struct TraceInfo;                      // Information about a trace point.
106 class TestInfoImpl;                    // Opaque implementation of TestInfo
107 class UnitTestImpl;                    // Opaque implementation of UnitTest
108 
109 // The text used in failure messages to indicate the start of the
110 // stack trace.
111 GTEST_API_ extern const char kStackTraceMarker[];
112 
113 // An IgnoredValue object can be implicitly constructed from ANY value.
114 class IgnoredValue {
115   struct Sink {};
116  public:
117   // This constructor template allows any value to be implicitly
118   // converted to IgnoredValue.  The object has no data member and
119   // doesn't try to remember anything about the argument.  We
120   // deliberately omit the 'explicit' keyword in order to allow the
121   // conversion to be implicit.
122   // Disable the conversion if T already has a magical conversion operator.
123   // Otherwise we get ambiguity.
124   template <typename T,
125             typename std::enable_if<!std::is_convertible<T, Sink>::value,
126                                     int>::type = 0>
IgnoredValue(const T &)127   IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
128 };
129 
130 // Appends the user-supplied message to the Google-Test-generated message.
131 GTEST_API_ std::string AppendUserMessage(
132     const std::string& gtest_msg, const Message& user_msg);
133 
134 #if GTEST_HAS_EXCEPTIONS
135 
136 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
137 /* an exported class was derived from a class that was not exported */)
138 
139 // This exception is thrown by (and only by) a failed Google Test
140 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
141 // are enabled).  We derive it from std::runtime_error, which is for
142 // errors presumably detectable only at run time.  Since
143 // std::runtime_error inherits from std::exception, many testing
144 // frameworks know how to extract and print the message inside it.
145 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
146  public:
147   explicit GoogleTestFailureException(const TestPartResult& failure);
148 };
149 
GTEST_DISABLE_MSC_WARNINGS_POP_()150 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4275
151 
152 #endif  // GTEST_HAS_EXCEPTIONS
153 
154 namespace edit_distance {
155 // Returns the optimal edits to go from 'left' to 'right'.
156 // All edits cost the same, with replace having lower priority than
157 // add/remove.
158 // Simple implementation of the Wagner-Fischer algorithm.
159 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
160 enum EditType { kMatch, kAdd, kRemove, kReplace };
161 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
162     const std::vector<size_t>& left, const std::vector<size_t>& right);
163 
164 // Same as above, but the input is represented as strings.
165 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
166     const std::vector<std::string>& left,
167     const std::vector<std::string>& right);
168 
169 // Create a diff of the input strings in Unified diff format.
170 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
171                                          const std::vector<std::string>& right,
172                                          size_t context = 2);
173 
174 }  // namespace edit_distance
175 
176 // Calculate the diff between 'left' and 'right' and return it in unified diff
177 // format.
178 // If not null, stores in 'total_line_count' the total number of lines found
179 // in left + right.
180 GTEST_API_ std::string DiffStrings(const std::string& left,
181                                    const std::string& right,
182                                    size_t* total_line_count);
183 
184 // Constructs and returns the message for an equality assertion
185 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
186 //
187 // The first four parameters are the expressions used in the assertion
188 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
189 // where foo is 5 and bar is 6, we have:
190 //
191 //   expected_expression: "foo"
192 //   actual_expression:   "bar"
193 //   expected_value:      "5"
194 //   actual_value:        "6"
195 //
196 // The ignoring_case parameter is true if and only if the assertion is a
197 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
198 // be inserted into the message.
199 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
200                                      const char* actual_expression,
201                                      const std::string& expected_value,
202                                      const std::string& actual_value,
203                                      bool ignoring_case);
204 
205 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
206 GTEST_API_ std::string GetBoolAssertionFailureMessage(
207     const AssertionResult& assertion_result,
208     const char* expression_text,
209     const char* actual_predicate_value,
210     const char* expected_predicate_value);
211 
212 // This template class represents an IEEE floating-point number
213 // (either single-precision or double-precision, depending on the
214 // template parameters).
215 //
216 // The purpose of this class is to do more sophisticated number
217 // comparison.  (Due to round-off error, etc, it's very unlikely that
218 // two floating-points will be equal exactly.  Hence a naive
219 // comparison by the == operation often doesn't work.)
220 //
221 // Format of IEEE floating-point:
222 //
223 //   The most-significant bit being the leftmost, an IEEE
224 //   floating-point looks like
225 //
226 //     sign_bit exponent_bits fraction_bits
227 //
228 //   Here, sign_bit is a single bit that designates the sign of the
229 //   number.
230 //
231 //   For float, there are 8 exponent bits and 23 fraction bits.
232 //
233 //   For double, there are 11 exponent bits and 52 fraction bits.
234 //
235 //   More details can be found at
236 //   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
237 //
238 // Template parameter:
239 //
240 //   RawType: the raw floating-point type (either float or double)
241 template <typename RawType>
242 class FloatingPoint {
243  public:
244   // Defines the unsigned integer type that has the same size as the
245   // floating point number.
246   typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
247 
248   // Constants.
249 
250   // # of bits in a number.
251   static const size_t kBitCount = 8*sizeof(RawType);
252 
253   // # of fraction bits in a number.
254   static const size_t kFractionBitCount =
255     std::numeric_limits<RawType>::digits - 1;
256 
257   // # of exponent bits in a number.
258   static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
259 
260   // The mask for the sign bit.
261   static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
262 
263   // The mask for the fraction bits.
264   static const Bits kFractionBitMask =
265     ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
266 
267   // The mask for the exponent bits.
268   static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
269 
270   // How many ULP's (Units in the Last Place) we want to tolerate when
271   // comparing two numbers.  The larger the value, the more error we
272   // allow.  A 0 value means that two numbers must be exactly the same
273   // to be considered equal.
274   //
275   // The maximum error of a single floating-point operation is 0.5
276   // units in the last place.  On Intel CPU's, all floating-point
277   // calculations are done with 80-bit precision, while double has 64
278   // bits.  Therefore, 4 should be enough for ordinary use.
279   //
280   // See the following article for more details on ULP:
281   // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
282   static const size_t kMaxUlps = 4;
283 
284   // Constructs a FloatingPoint from a raw floating-point number.
285   //
286   // On an Intel CPU, passing a non-normalized NAN (Not a Number)
287   // around may change its bits, although the new value is guaranteed
288   // to be also a NAN.  Therefore, don't expect this constructor to
289   // preserve the bits in x when x is a NAN.
FloatingPoint(const RawType & x)290   explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
291 
292   // Static methods
293 
294   // Reinterprets a bit pattern as a floating-point number.
295   //
296   // This function is needed to test the AlmostEquals() method.
ReinterpretBits(const Bits bits)297   static RawType ReinterpretBits(const Bits bits) {
298     FloatingPoint fp(0);
299     fp.u_.bits_ = bits;
300     return fp.u_.value_;
301   }
302 
303   // Returns the floating-point number that represent positive infinity.
Infinity()304   static RawType Infinity() {
305     return ReinterpretBits(kExponentBitMask);
306   }
307 
308   // Returns the maximum representable finite floating-point number.
309   static RawType Max();
310 
311   // Non-static methods
312 
313   // Returns the bits that represents this number.
bits()314   const Bits &bits() const { return u_.bits_; }
315 
316   // Returns the exponent bits of this number.
exponent_bits()317   Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
318 
319   // Returns the fraction bits of this number.
fraction_bits()320   Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
321 
322   // Returns the sign bit of this number.
sign_bit()323   Bits sign_bit() const { return kSignBitMask & u_.bits_; }
324 
325   // Returns true if and only if this is NAN (not a number).
is_nan()326   bool is_nan() const {
327     // It's a NAN if the exponent bits are all ones and the fraction
328     // bits are not entirely zeros.
329     return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
330   }
331 
332   // Returns true if and only if this number is at most kMaxUlps ULP's away
333   // from rhs.  In particular, this function:
334   //
335   //   - returns false if either number is (or both are) NAN.
336   //   - treats really large numbers as almost equal to infinity.
337   //   - thinks +0.0 and -0.0 are 0 DLP's apart.
AlmostEquals(const FloatingPoint & rhs)338   bool AlmostEquals(const FloatingPoint& rhs) const {
339     // The IEEE standard says that any comparison operation involving
340     // a NAN must return false.
341     if (is_nan() || rhs.is_nan()) return false;
342 
343     return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
344         <= kMaxUlps;
345   }
346 
347  private:
348   // The data type used to store the actual floating-point number.
349   union FloatingPointUnion {
350     RawType value_;  // The raw floating-point number.
351     Bits bits_;      // The bits that represent the number.
352   };
353 
354   // Converts an integer from the sign-and-magnitude representation to
355   // the biased representation.  More precisely, let N be 2 to the
356   // power of (kBitCount - 1), an integer x is represented by the
357   // unsigned number x + N.
358   //
359   // For instance,
360   //
361   //   -N + 1 (the most negative number representable using
362   //          sign-and-magnitude) is represented by 1;
363   //   0      is represented by N; and
364   //   N - 1  (the biggest number representable using
365   //          sign-and-magnitude) is represented by 2N - 1.
366   //
367   // Read http://en.wikipedia.org/wiki/Signed_number_representations
368   // for more details on signed number representations.
SignAndMagnitudeToBiased(const Bits & sam)369   static Bits SignAndMagnitudeToBiased(const Bits &sam) {
370     if (kSignBitMask & sam) {
371       // sam represents a negative number.
372       return ~sam + 1;
373     } else {
374       // sam represents a positive number.
375       return kSignBitMask | sam;
376     }
377   }
378 
379   // Given two numbers in the sign-and-magnitude representation,
380   // returns the distance between them as an unsigned number.
DistanceBetweenSignAndMagnitudeNumbers(const Bits & sam1,const Bits & sam2)381   static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
382                                                      const Bits &sam2) {
383     const Bits biased1 = SignAndMagnitudeToBiased(sam1);
384     const Bits biased2 = SignAndMagnitudeToBiased(sam2);
385     return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
386   }
387 
388   FloatingPointUnion u_;
389 };
390 
391 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
392 // macro defined by <windows.h>.
393 template <>
Max()394 inline float FloatingPoint<float>::Max() { return FLT_MAX; }
395 template <>
Max()396 inline double FloatingPoint<double>::Max() { return DBL_MAX; }
397 
398 // Typedefs the instances of the FloatingPoint template class that we
399 // care to use.
400 typedef FloatingPoint<float> Float;
401 typedef FloatingPoint<double> Double;
402 
403 // In order to catch the mistake of putting tests that use different
404 // test fixture classes in the same test suite, we need to assign
405 // unique IDs to fixture classes and compare them.  The TypeId type is
406 // used to hold such IDs.  The user should treat TypeId as an opaque
407 // type: the only operation allowed on TypeId values is to compare
408 // them for equality using the == operator.
409 typedef const void* TypeId;
410 
411 template <typename T>
412 class TypeIdHelper {
413  public:
414   // dummy_ must not have a const type.  Otherwise an overly eager
415   // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
416   // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
417   static bool dummy_;
418 };
419 
420 template <typename T>
421 bool TypeIdHelper<T>::dummy_ = false;
422 
423 // GetTypeId<T>() returns the ID of type T.  Different values will be
424 // returned for different types.  Calling the function twice with the
425 // same type argument is guaranteed to return the same ID.
426 template <typename T>
GetTypeId()427 TypeId GetTypeId() {
428   // The compiler is required to allocate a different
429   // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
430   // the template.  Therefore, the address of dummy_ is guaranteed to
431   // be unique.
432   return &(TypeIdHelper<T>::dummy_);
433 }
434 
435 // Returns the type ID of ::testing::Test.  Always call this instead
436 // of GetTypeId< ::testing::Test>() to get the type ID of
437 // ::testing::Test, as the latter may give the wrong result due to a
438 // suspected linker bug when compiling Google Test as a Mac OS X
439 // framework.
440 GTEST_API_ TypeId GetTestTypeId();
441 
442 // Defines the abstract factory interface that creates instances
443 // of a Test object.
444 class TestFactoryBase {
445  public:
~TestFactoryBase()446   virtual ~TestFactoryBase() {}
447 
448   // Creates a test instance to run. The instance is both created and destroyed
449   // within TestInfoImpl::Run()
450   virtual Test* CreateTest() = 0;
451 
452  protected:
TestFactoryBase()453   TestFactoryBase() {}
454 
455  private:
456   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
457 };
458 
459 // This class provides implementation of TeastFactoryBase interface.
460 // It is used in TEST and TEST_F macros.
461 template <class TestClass>
462 class TestFactoryImpl : public TestFactoryBase {
463  public:
CreateTest()464   Test* CreateTest() override { return new TestClass; }
465 };
466 
467 #if GTEST_OS_WINDOWS
468 
469 // Predicate-formatters for implementing the HRESULT checking macros
470 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
471 // We pass a long instead of HRESULT to avoid causing an
472 // include dependency for the HRESULT type.
473 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
474                                             long hr);  // NOLINT
475 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
476                                             long hr);  // NOLINT
477 
478 #endif  // GTEST_OS_WINDOWS
479 
480 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
481 using SetUpTestSuiteFunc = void (*)();
482 using TearDownTestSuiteFunc = void (*)();
483 
484 struct CodeLocation {
CodeLocationCodeLocation485   CodeLocation(const std::string& a_file, int a_line)
486       : file(a_file), line(a_line) {}
487 
488   std::string file;
489   int line;
490 };
491 
492 //  Helper to identify which setup function for TestCase / TestSuite to call.
493 //  Only one function is allowed, either TestCase or TestSute but not both.
494 
495 // Utility functions to help SuiteApiResolver
496 using SetUpTearDownSuiteFuncType = void (*)();
497 
GetNotDefaultOrNull(SetUpTearDownSuiteFuncType a,SetUpTearDownSuiteFuncType def)498 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
499     SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
500   return a == def ? nullptr : a;
501 }
502 
503 template <typename T>
504 //  Note that SuiteApiResolver inherits from T because
505 //  SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
506 //  SuiteApiResolver can access them.
507 struct SuiteApiResolver : T {
508   // testing::Test is only forward declared at this point. So we make it a
509   // dependend class for the compiler to be OK with it.
510   using Test =
511       typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
512 
GetSetUpCaseOrSuiteSuiteApiResolver513   static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
514                                                         int line_num) {
515     SetUpTearDownSuiteFuncType test_case_fp =
516         GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
517     SetUpTearDownSuiteFuncType test_suite_fp =
518         GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
519 
520     GTEST_CHECK_(!test_case_fp || !test_suite_fp)
521         << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
522            "make sure there is only one present at "
523         << filename << ":" << line_num;
524 
525     return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
526   }
527 
GetTearDownCaseOrSuiteSuiteApiResolver528   static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
529                                                            int line_num) {
530     SetUpTearDownSuiteFuncType test_case_fp =
531         GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
532     SetUpTearDownSuiteFuncType test_suite_fp =
533         GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
534 
535     GTEST_CHECK_(!test_case_fp || !test_suite_fp)
536         << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
537            " please make sure there is only one present at"
538         << filename << ":" << line_num;
539 
540     return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
541   }
542 };
543 
544 // Creates a new TestInfo object and registers it with Google Test;
545 // returns the created object.
546 //
547 // Arguments:
548 //
549 //   test_suite_name:   name of the test suite
550 //   name:             name of the test
551 //   type_param        the name of the test's type parameter, or NULL if
552 //                     this is not a typed or a type-parameterized test.
553 //   value_param       text representation of the test's value parameter,
554 //                     or NULL if this is not a type-parameterized test.
555 //   code_location:    code location where the test is defined
556 //   fixture_class_id: ID of the test fixture class
557 //   set_up_tc:        pointer to the function that sets up the test suite
558 //   tear_down_tc:     pointer to the function that tears down the test suite
559 //   factory:          pointer to the factory that creates a test object.
560 //                     The newly created TestInfo instance will assume
561 //                     ownership of the factory object.
562 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
563     const char* test_suite_name, const char* name, const char* type_param,
564     const char* value_param, CodeLocation code_location,
565     TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
566     TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
567 
568 // If *pstr starts with the given prefix, modifies *pstr to be right
569 // past the prefix and returns true; otherwise leaves *pstr unchanged
570 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
571 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
572 
573 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
574 
575 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
576 /* class A needs to have dll-interface to be used by clients of class B */)
577 
578 // State of the definition of a type-parameterized test suite.
579 class GTEST_API_ TypedTestSuitePState {
580  public:
TypedTestSuitePState()581   TypedTestSuitePState() : registered_(false) {}
582 
583   // Adds the given test name to defined_test_names_ and return true
584   // if the test suite hasn't been registered; otherwise aborts the
585   // program.
AddTestName(const char * file,int line,const char * case_name,const char * test_name)586   bool AddTestName(const char* file, int line, const char* case_name,
587                    const char* test_name) {
588     if (registered_) {
589       fprintf(stderr,
590               "%s Test %s must be defined before "
591               "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
592               FormatFileLocation(file, line).c_str(), test_name, case_name);
593       fflush(stderr);
594       posix::Abort();
595     }
596     registered_tests_.insert(
597         ::std::make_pair(test_name, CodeLocation(file, line)));
598     return true;
599   }
600 
TestExists(const std::string & test_name)601   bool TestExists(const std::string& test_name) const {
602     return registered_tests_.count(test_name) > 0;
603   }
604 
GetCodeLocation(const std::string & test_name)605   const CodeLocation& GetCodeLocation(const std::string& test_name) const {
606     RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
607     GTEST_CHECK_(it != registered_tests_.end());
608     return it->second;
609   }
610 
611   // Verifies that registered_tests match the test names in
612   // defined_test_names_; returns registered_tests if successful, or
613   // aborts the program otherwise.
614   const char* VerifyRegisteredTestNames(
615       const char* file, int line, const char* registered_tests);
616 
617  private:
618   typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
619 
620   bool registered_;
621   RegisteredTestsMap registered_tests_;
622 };
623 
624 //  Legacy API is deprecated but still available
625 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
626 using TypedTestCasePState = TypedTestSuitePState;
627 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
628 
GTEST_DISABLE_MSC_WARNINGS_POP_()629 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
630 
631 // Skips to the first non-space char after the first comma in 'str';
632 // returns NULL if no comma is found in 'str'.
633 inline const char* SkipComma(const char* str) {
634   const char* comma = strchr(str, ',');
635   if (comma == nullptr) {
636     return nullptr;
637   }
638   while (IsSpace(*(++comma))) {}
639   return comma;
640 }
641 
642 // Returns the prefix of 'str' before the first comma in it; returns
643 // the entire string if it contains no comma.
GetPrefixUntilComma(const char * str)644 inline std::string GetPrefixUntilComma(const char* str) {
645   const char* comma = strchr(str, ',');
646   return comma == nullptr ? str : std::string(str, comma);
647 }
648 
649 // Splits a given string on a given delimiter, populating a given
650 // vector with the fields.
651 void SplitString(const ::std::string& str, char delimiter,
652                  ::std::vector< ::std::string>* dest);
653 
654 // The default argument to the template below for the case when the user does
655 // not provide a name generator.
656 struct DefaultNameGenerator {
657   template <typename T>
GetNameDefaultNameGenerator658   static std::string GetName(int i) {
659     return StreamableToString(i);
660   }
661 };
662 
663 template <typename Provided = DefaultNameGenerator>
664 struct NameGeneratorSelector {
665   typedef Provided type;
666 };
667 
668 template <typename NameGenerator>
GenerateNamesRecursively(Types0,std::vector<std::string> *,int)669 void GenerateNamesRecursively(Types0, std::vector<std::string>*, int) {}
670 
671 template <typename NameGenerator, typename Types>
GenerateNamesRecursively(Types,std::vector<std::string> * result,int i)672 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
673   result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
674   GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
675                                           i + 1);
676 }
677 
678 template <typename NameGenerator, typename Types>
GenerateNames()679 std::vector<std::string> GenerateNames() {
680   std::vector<std::string> result;
681   GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
682   return result;
683 }
684 
685 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
686 // registers a list of type-parameterized tests with Google Test.  The
687 // return value is insignificant - we just need to return something
688 // such that we can call this function in a namespace scope.
689 //
690 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
691 // template parameter.  It's defined in gtest-type-util.h.
692 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
693 class TypeParameterizedTest {
694  public:
695   // 'index' is the index of the test in the type list 'Types'
696   // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
697   // Types).  Valid values for 'index' are [0, N - 1] where N is the
698   // length of Types.
699   static bool Register(const char* prefix, const CodeLocation& code_location,
700                        const char* case_name, const char* test_names, int index,
701                        const std::vector<std::string>& type_names =
702                            GenerateNames<DefaultNameGenerator, Types>()) {
703     typedef typename Types::Head Type;
704     typedef Fixture<Type> FixtureClass;
705     typedef typename GTEST_BIND_(TestSel, Type) TestClass;
706 
707     // First, registers the first type-parameterized test in the type
708     // list.
709     MakeAndRegisterTestInfo(
710         (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
711          "/" + type_names[static_cast<size_t>(index)])
712             .c_str(),
713         StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
714         GetTypeName<Type>().c_str(),
715         nullptr,  // No value parameter.
716         code_location, GetTypeId<FixtureClass>(),
717         SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(
718             code_location.file.c_str(), code_location.line),
719         SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(
720             code_location.file.c_str(), code_location.line),
721         new TestFactoryImpl<TestClass>);
722 
723     // Next, recurses (at compile time) with the tail of the type list.
724     return TypeParameterizedTest<Fixture, TestSel,
725                                  typename Types::Tail>::Register(prefix,
726                                                                  code_location,
727                                                                  case_name,
728                                                                  test_names,
729                                                                  index + 1,
730                                                                  type_names);
731   }
732 };
733 
734 // The base case for the compile time recursion.
735 template <GTEST_TEMPLATE_ Fixture, class TestSel>
736 class TypeParameterizedTest<Fixture, TestSel, Types0> {
737  public:
738   static bool Register(const char* /*prefix*/, const CodeLocation&,
739                        const char* /*case_name*/, const char* /*test_names*/,
740                        int /*index*/,
741                        const std::vector<std::string>& =
742                            std::vector<std::string>() /*type_names*/) {
743     return true;
744   }
745 };
746 
747 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
748 // registers *all combinations* of 'Tests' and 'Types' with Google
749 // Test.  The return value is insignificant - we just need to return
750 // something such that we can call this function in a namespace scope.
751 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
752 class TypeParameterizedTestSuite {
753  public:
754   static bool Register(const char* prefix, CodeLocation code_location,
755                        const TypedTestSuitePState* state, const char* case_name,
756                        const char* test_names,
757                        const std::vector<std::string>& type_names =
758                            GenerateNames<DefaultNameGenerator, Types>()) {
759     std::string test_name = StripTrailingSpaces(
760         GetPrefixUntilComma(test_names));
761     if (!state->TestExists(test_name)) {
762       fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
763               case_name, test_name.c_str(),
764               FormatFileLocation(code_location.file.c_str(),
765                                  code_location.line).c_str());
766       fflush(stderr);
767       posix::Abort();
768     }
769     const CodeLocation& test_location = state->GetCodeLocation(test_name);
770 
771     typedef typename Tests::Head Head;
772 
773     // First, register the first test in 'Test' for each type in 'Types'.
774     TypeParameterizedTest<Fixture, Head, Types>::Register(
775         prefix, test_location, case_name, test_names, 0, type_names);
776 
777     // Next, recurses (at compile time) with the tail of the test list.
778     return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
779                                       Types>::Register(prefix, code_location,
780                                                        state, case_name,
781                                                        SkipComma(test_names),
782                                                        type_names);
783   }
784 };
785 
786 // The base case for the compile time recursion.
787 template <GTEST_TEMPLATE_ Fixture, typename Types>
788 class TypeParameterizedTestSuite<Fixture, Templates0, Types> {
789  public:
790   static bool Register(const char* /*prefix*/, const CodeLocation&,
791                        const TypedTestSuitePState* /*state*/,
792                        const char* /*case_name*/, const char* /*test_names*/,
793                        const std::vector<std::string>& =
794                            std::vector<std::string>() /*type_names*/) {
795     return true;
796   }
797 };
798 
799 #endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
800 
801 // Returns the current OS stack trace as an std::string.
802 //
803 // The maximum number of stack frames to be included is specified by
804 // the gtest_stack_trace_depth flag.  The skip_count parameter
805 // specifies the number of top frames to be skipped, which doesn't
806 // count against the number of frames to be included.
807 //
808 // For example, if Foo() calls Bar(), which in turn calls
809 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
810 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
811 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
812     UnitTest* unit_test, int skip_count);
813 
814 // Helpers for suppressing warnings on unreachable code or constant
815 // condition.
816 
817 // Always returns true.
818 GTEST_API_ bool AlwaysTrue();
819 
820 // Always returns false.
AlwaysFalse()821 inline bool AlwaysFalse() { return !AlwaysTrue(); }
822 
823 // Helper for suppressing false warning from Clang on a const char*
824 // variable declared in a conditional expression always being NULL in
825 // the else branch.
826 struct GTEST_API_ ConstCharPtr {
ConstCharPtrConstCharPtr827   ConstCharPtr(const char* str) : value(str) {}
828   operator bool() const { return true; }
829   const char* value;
830 };
831 
832 // A simple Linear Congruential Generator for generating random
833 // numbers with a uniform distribution.  Unlike rand() and srand(), it
834 // doesn't use global state (and therefore can't interfere with user
835 // code).  Unlike rand_r(), it's portable.  An LCG isn't very random,
836 // but it's good enough for our purposes.
837 class GTEST_API_ Random {
838  public:
839   static const UInt32 kMaxRange = 1u << 31;
840 
Random(UInt32 seed)841   explicit Random(UInt32 seed) : state_(seed) {}
842 
Reseed(UInt32 seed)843   void Reseed(UInt32 seed) { state_ = seed; }
844 
845   // Generates a random number from [0, range).  Crashes if 'range' is
846   // 0 or greater than kMaxRange.
847   UInt32 Generate(UInt32 range);
848 
849  private:
850   UInt32 state_;
851   GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
852 };
853 
854 // Turns const U&, U&, const U, and U all into U.
855 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
856   typename std::remove_const<typename std::remove_reference<T>::type>::type
857 
858 // IsAProtocolMessage<T>::value is a compile-time bool constant that's
859 // true if and only if T is type proto2::Message or a subclass of it.
860 template <typename T>
861 struct IsAProtocolMessage
862     : public bool_constant<
863           std::is_convertible<const T*, const ::proto2::Message*>::value> {};
864 
865 // When the compiler sees expression IsContainerTest<C>(0), if C is an
866 // STL-style container class, the first overload of IsContainerTest
867 // will be viable (since both C::iterator* and C::const_iterator* are
868 // valid types and NULL can be implicitly converted to them).  It will
869 // be picked over the second overload as 'int' is a perfect match for
870 // the type of argument 0.  If C::iterator or C::const_iterator is not
871 // a valid type, the first overload is not viable, and the second
872 // overload will be picked.  Therefore, we can determine whether C is
873 // a container class by checking the type of IsContainerTest<C>(0).
874 // The value of the expression is insignificant.
875 //
876 // In C++11 mode we check the existence of a const_iterator and that an
877 // iterator is properly implemented for the container.
878 //
879 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
880 // The reason is that C++ injects the name of a class as a member of the
881 // class itself (e.g. you can refer to class iterator as either
882 // 'iterator' or 'iterator::iterator').  If we look for C::iterator
883 // only, for example, we would mistakenly think that a class named
884 // iterator is an STL container.
885 //
886 // Also note that the simpler approach of overloading
887 // IsContainerTest(typename C::const_iterator*) and
888 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
889 typedef int IsContainer;
890 template <class C,
891           class Iterator = decltype(::std::declval<const C&>().begin()),
892           class = decltype(::std::declval<const C&>().end()),
893           class = decltype(++::std::declval<Iterator&>()),
894           class = decltype(*::std::declval<Iterator>()),
895           class = typename C::const_iterator>
IsContainerTest(int)896 IsContainer IsContainerTest(int /* dummy */) {
897   return 0;
898 }
899 
900 typedef char IsNotContainer;
901 template <class C>
IsContainerTest(long)902 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
903 
904 // Trait to detect whether a type T is a hash table.
905 // The heuristic used is that the type contains an inner type `hasher` and does
906 // not contain an inner type `reverse_iterator`.
907 // If the container is iterable in reverse, then order might actually matter.
908 template <typename T>
909 struct IsHashTable {
910  private:
911   template <typename U>
912   static char test(typename U::hasher*, typename U::reverse_iterator*);
913   template <typename U>
914   static int test(typename U::hasher*, ...);
915   template <typename U>
916   static char test(...);
917 
918  public:
919   static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
920 };
921 
922 template <typename T>
923 const bool IsHashTable<T>::value;
924 
925 template <typename C,
926           bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
927 struct IsRecursiveContainerImpl;
928 
929 template <typename C>
930 struct IsRecursiveContainerImpl<C, false> : public std::false_type {};
931 
932 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
933 // obey the same inconsistencies as the IsContainerTest, namely check if
934 // something is a container is relying on only const_iterator in C++11 and
935 // is relying on both const_iterator and iterator otherwise
936 template <typename C>
937 struct IsRecursiveContainerImpl<C, true> {
938   using value_type = decltype(*std::declval<typename C::const_iterator>());
939   using type =
940       std::is_same<typename std::remove_const<
941                        typename std::remove_reference<value_type>::type>::type,
942                    C>;
943 };
944 
945 // IsRecursiveContainer<Type> is a unary compile-time predicate that
946 // evaluates whether C is a recursive container type. A recursive container
947 // type is a container type whose value_type is equal to the container type
948 // itself. An example for a recursive container type is
949 // boost::filesystem::path, whose iterator has a value_type that is equal to
950 // boost::filesystem::path.
951 template <typename C>
952 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
953 
954 // Utilities for native arrays.
955 
956 // ArrayEq() compares two k-dimensional native arrays using the
957 // elements' operator==, where k can be any integer >= 0.  When k is
958 // 0, ArrayEq() degenerates into comparing a single pair of values.
959 
960 template <typename T, typename U>
961 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
962 
963 // This generic version is used when k is 0.
964 template <typename T, typename U>
965 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
966 
967 // This overload is used when k >= 1.
968 template <typename T, typename U, size_t N>
969 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
970   return internal::ArrayEq(lhs, N, rhs);
971 }
972 
973 // This helper reduces code bloat.  If we instead put its logic inside
974 // the previous ArrayEq() function, arrays with different sizes would
975 // lead to different copies of the template code.
976 template <typename T, typename U>
977 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
978   for (size_t i = 0; i != size; i++) {
979     if (!internal::ArrayEq(lhs[i], rhs[i]))
980       return false;
981   }
982   return true;
983 }
984 
985 // Finds the first element in the iterator range [begin, end) that
986 // equals elem.  Element may be a native array type itself.
987 template <typename Iter, typename Element>
988 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
989   for (Iter it = begin; it != end; ++it) {
990     if (internal::ArrayEq(*it, elem))
991       return it;
992   }
993   return end;
994 }
995 
996 // CopyArray() copies a k-dimensional native array using the elements'
997 // operator=, where k can be any integer >= 0.  When k is 0,
998 // CopyArray() degenerates into copying a single value.
999 
1000 template <typename T, typename U>
1001 void CopyArray(const T* from, size_t size, U* to);
1002 
1003 // This generic version is used when k is 0.
1004 template <typename T, typename U>
1005 inline void CopyArray(const T& from, U* to) { *to = from; }
1006 
1007 // This overload is used when k >= 1.
1008 template <typename T, typename U, size_t N>
1009 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
1010   internal::CopyArray(from, N, *to);
1011 }
1012 
1013 // This helper reduces code bloat.  If we instead put its logic inside
1014 // the previous CopyArray() function, arrays with different sizes
1015 // would lead to different copies of the template code.
1016 template <typename T, typename U>
1017 void CopyArray(const T* from, size_t size, U* to) {
1018   for (size_t i = 0; i != size; i++) {
1019     internal::CopyArray(from[i], to + i);
1020   }
1021 }
1022 
1023 // The relation between an NativeArray object (see below) and the
1024 // native array it represents.
1025 // We use 2 different structs to allow non-copyable types to be used, as long
1026 // as RelationToSourceReference() is passed.
1027 struct RelationToSourceReference {};
1028 struct RelationToSourceCopy {};
1029 
1030 // Adapts a native array to a read-only STL-style container.  Instead
1031 // of the complete STL container concept, this adaptor only implements
1032 // members useful for Google Mock's container matchers.  New members
1033 // should be added as needed.  To simplify the implementation, we only
1034 // support Element being a raw type (i.e. having no top-level const or
1035 // reference modifier).  It's the client's responsibility to satisfy
1036 // this requirement.  Element can be an array type itself (hence
1037 // multi-dimensional arrays are supported).
1038 template <typename Element>
1039 class NativeArray {
1040  public:
1041   // STL-style container typedefs.
1042   typedef Element value_type;
1043   typedef Element* iterator;
1044   typedef const Element* const_iterator;
1045 
1046   // Constructs from a native array. References the source.
1047   NativeArray(const Element* array, size_t count, RelationToSourceReference) {
1048     InitRef(array, count);
1049   }
1050 
1051   // Constructs from a native array. Copies the source.
1052   NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
1053     InitCopy(array, count);
1054   }
1055 
1056   // Copy constructor.
1057   NativeArray(const NativeArray& rhs) {
1058     (this->*rhs.clone_)(rhs.array_, rhs.size_);
1059   }
1060 
1061   ~NativeArray() {
1062     if (clone_ != &NativeArray::InitRef)
1063       delete[] array_;
1064   }
1065 
1066   // STL-style container methods.
1067   size_t size() const { return size_; }
1068   const_iterator begin() const { return array_; }
1069   const_iterator end() const { return array_ + size_; }
1070   bool operator==(const NativeArray& rhs) const {
1071     return size() == rhs.size() &&
1072         ArrayEq(begin(), size(), rhs.begin());
1073   }
1074 
1075  private:
1076   static_assert(!std::is_const<Element>::value, "Type must not be const");
1077   static_assert(!std::is_reference<Element>::value,
1078                 "Type must not be a reference");
1079 
1080   // Initializes this object with a copy of the input.
1081   void InitCopy(const Element* array, size_t a_size) {
1082     Element* const copy = new Element[a_size];
1083     CopyArray(array, a_size, copy);
1084     array_ = copy;
1085     size_ = a_size;
1086     clone_ = &NativeArray::InitCopy;
1087   }
1088 
1089   // Initializes this object with a reference of the input.
1090   void InitRef(const Element* array, size_t a_size) {
1091     array_ = array;
1092     size_ = a_size;
1093     clone_ = &NativeArray::InitRef;
1094   }
1095 
1096   const Element* array_;
1097   size_t size_;
1098   void (NativeArray::*clone_)(const Element*, size_t);
1099 
1100   GTEST_DISALLOW_ASSIGN_(NativeArray);
1101 };
1102 
1103 // Backport of std::index_sequence.
1104 template <size_t... Is>
1105 struct IndexSequence {
1106   using type = IndexSequence;
1107 };
1108 
1109 // Double the IndexSequence, and one if plus_one is true.
1110 template <bool plus_one, typename T, size_t sizeofT>
1111 struct DoubleSequence;
1112 template <size_t... I, size_t sizeofT>
1113 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
1114   using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
1115 };
1116 template <size_t... I, size_t sizeofT>
1117 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
1118   using type = IndexSequence<I..., (sizeofT + I)...>;
1119 };
1120 
1121 // Backport of std::make_index_sequence.
1122 // It uses O(ln(N)) instantiation depth.
1123 template <size_t N>
1124 struct MakeIndexSequence
1125     : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
1126                      N / 2>::type {};
1127 
1128 template <>
1129 struct MakeIndexSequence<0> : IndexSequence<> {};
1130 
1131 // FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
1132 // but it is O(N^2) in total instantiations. Not sure if this is the best
1133 // tradeoff, as it will make it somewhat slow to compile.
1134 template <typename T, size_t, size_t>
1135 struct ElemFromListImpl {};
1136 
1137 template <typename T, size_t I>
1138 struct ElemFromListImpl<T, I, I> {
1139   using type = T;
1140 };
1141 
1142 // Get the Nth element from T...
1143 // It uses O(1) instantiation depth.
1144 template <size_t N, typename I, typename... T>
1145 struct ElemFromList;
1146 
1147 template <size_t N, size_t... I, typename... T>
1148 struct ElemFromList<N, IndexSequence<I...>, T...>
1149     : ElemFromListImpl<T, N, I>... {};
1150 
1151 template <typename... T>
1152 class FlatTuple;
1153 
1154 template <typename Derived, size_t I>
1155 struct FlatTupleElemBase;
1156 
1157 template <typename... T, size_t I>
1158 struct FlatTupleElemBase<FlatTuple<T...>, I> {
1159   using value_type =
1160       typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type,
1161                             T...>::type;
1162   FlatTupleElemBase() = default;
1163   explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
1164   value_type value;
1165 };
1166 
1167 template <typename Derived, typename Idx>
1168 struct FlatTupleBase;
1169 
1170 template <size_t... Idx, typename... T>
1171 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
1172     : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
1173   using Indices = IndexSequence<Idx...>;
1174   FlatTupleBase() = default;
1175   explicit FlatTupleBase(T... t)
1176       : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
1177 };
1178 
1179 // Analog to std::tuple but with different tradeoffs.
1180 // This class minimizes the template instantiation depth, thus allowing more
1181 // elements that std::tuple would. std::tuple has been seen to require an
1182 // instantiation depth of more than 10x the number of elements in some
1183 // implementations.
1184 // FlatTuple and ElemFromList are not recursive and have a fixed depth
1185 // regardless of T...
1186 // MakeIndexSequence, on the other hand, it is recursive but with an
1187 // instantiation depth of O(ln(N)).
1188 template <typename... T>
1189 class FlatTuple
1190     : private FlatTupleBase<FlatTuple<T...>,
1191                             typename MakeIndexSequence<sizeof...(T)>::type> {
1192   using Indices = typename FlatTuple::FlatTupleBase::Indices;
1193 
1194  public:
1195   FlatTuple() = default;
1196   explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
1197 
1198   template <size_t I>
1199   const typename ElemFromList<I, Indices, T...>::type& Get() const {
1200     return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1201   }
1202 
1203   template <size_t I>
1204   typename ElemFromList<I, Indices, T...>::type& Get() {
1205     return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1206   }
1207 };
1208 
1209 // Utility functions to be called with static_assert to induce deprecation
1210 // warnings.
1211 GTEST_INTERNAL_DEPRECATED(
1212     "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1213     "INSTANTIATE_TEST_SUITE_P")
1214 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1215 
1216 GTEST_INTERNAL_DEPRECATED(
1217     "TYPED_TEST_CASE_P is deprecated, please use "
1218     "TYPED_TEST_SUITE_P")
1219 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1220 
1221 GTEST_INTERNAL_DEPRECATED(
1222     "TYPED_TEST_CASE is deprecated, please use "
1223     "TYPED_TEST_SUITE")
1224 constexpr bool TypedTestCaseIsDeprecated() { return true; }
1225 
1226 GTEST_INTERNAL_DEPRECATED(
1227     "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1228     "REGISTER_TYPED_TEST_SUITE_P")
1229 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1230 
1231 GTEST_INTERNAL_DEPRECATED(
1232     "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1233     "INSTANTIATE_TYPED_TEST_SUITE_P")
1234 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1235 
1236 }  // namespace internal
1237 }  // namespace testing
1238 
1239 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1240   ::testing::internal::AssertHelper(result_type, file, line, message) \
1241     = ::testing::Message()
1242 
1243 #define GTEST_MESSAGE_(message, result_type) \
1244   GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1245 
1246 #define GTEST_FATAL_FAILURE_(message) \
1247   return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1248 
1249 #define GTEST_NONFATAL_FAILURE_(message) \
1250   GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1251 
1252 #define GTEST_SUCCESS_(message) \
1253   GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1254 
1255 #define GTEST_SKIP_(message) \
1256   return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1257 
1258 // Suppress MSVC warning 4072 (unreachable code) for the code following
1259 // statement if it returns or throws (or doesn't return or throw in some
1260 // situations).
1261 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1262   if (::testing::internal::AlwaysTrue()) { statement; }
1263 
1264 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1265   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1266   if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1267     bool gtest_caught_expected = false; \
1268     try { \
1269       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1270     } \
1271     catch (expected_exception const&) { \
1272       gtest_caught_expected = true; \
1273     } \
1274     catch (...) { \
1275       gtest_msg.value = \
1276           "Expected: " #statement " throws an exception of type " \
1277           #expected_exception ".\n  Actual: it throws a different type."; \
1278       goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1279     } \
1280     if (!gtest_caught_expected) { \
1281       gtest_msg.value = \
1282           "Expected: " #statement " throws an exception of type " \
1283           #expected_exception ".\n  Actual: it throws nothing."; \
1284       goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1285     } \
1286   } else \
1287     GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1288       fail(gtest_msg.value)
1289 
1290 #define GTEST_TEST_NO_THROW_(statement, fail) \
1291   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1292   if (::testing::internal::AlwaysTrue()) { \
1293     try { \
1294       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1295     } \
1296     catch (...) { \
1297       goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1298     } \
1299   } else \
1300     GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1301       fail("Expected: " #statement " doesn't throw an exception.\n" \
1302            "  Actual: it throws.")
1303 
1304 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1305   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1306   if (::testing::internal::AlwaysTrue()) { \
1307     bool gtest_caught_any = false; \
1308     try { \
1309       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1310     } \
1311     catch (...) { \
1312       gtest_caught_any = true; \
1313     } \
1314     if (!gtest_caught_any) { \
1315       goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1316     } \
1317   } else \
1318     GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1319       fail("Expected: " #statement " throws an exception.\n" \
1320            "  Actual: it doesn't.")
1321 
1322 
1323 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1324 // either a boolean expression or an AssertionResult. text is a textual
1325 // represenation of expression as it was passed into the EXPECT_TRUE.
1326 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1327   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1328   if (const ::testing::AssertionResult gtest_ar_ = \
1329       ::testing::AssertionResult(expression)) \
1330     ; \
1331   else \
1332     fail(::testing::internal::GetBoolAssertionFailureMessage(\
1333         gtest_ar_, text, #actual, #expected).c_str())
1334 
1335 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1336   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1337   if (::testing::internal::AlwaysTrue()) { \
1338     ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1339     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1340     if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1341       goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1342     } \
1343   } else \
1344     GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1345       fail("Expected: " #statement " doesn't generate new fatal " \
1346            "failures in the current thread.\n" \
1347            "  Actual: it does.")
1348 
1349 // Expands to the name of the class that implements the given test.
1350 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1351   test_suite_name##_##test_name##_Test
1352 
1353 // Helper macro for defining tests.
1354 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id)      \
1355   static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1,                \
1356                 "test_suite_name must not be empty");                         \
1357   static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1,                      \
1358                 "test_name must not be empty");                               \
1359   class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                    \
1360       : public parent_class {                                                 \
1361    public:                                                                    \
1362     GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {}                   \
1363                                                                               \
1364    private:                                                                   \
1365     virtual void TestBody();                                                  \
1366     static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;     \
1367     GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,   \
1368                                                            test_name));       \
1369   };                                                                          \
1370                                                                               \
1371   ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name,          \
1372                                                     test_name)::test_info_ =  \
1373       ::testing::internal::MakeAndRegisterTestInfo(                           \
1374           #test_suite_name, #test_name, nullptr, nullptr,                     \
1375           ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1376           ::testing::internal::SuiteApiResolver<                              \
1377               parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__),         \
1378           ::testing::internal::SuiteApiResolver<                              \
1379               parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__),      \
1380           new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_(    \
1381               test_suite_name, test_name)>);                                  \
1382   void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1383 
1384 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
1385