Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-07 08:19:53

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 //
0030 // Author: wan@google.com (Zhanyong Wan)
0031 
0032 // Google Mock - a framework for writing C++ mock classes.
0033 //
0034 // This file implements the ON_CALL() and EXPECT_CALL() macros.
0035 //
0036 // A user can use the ON_CALL() macro to specify the default action of
0037 // a mock method.  The syntax is:
0038 //
0039 //   ON_CALL(mock_object, Method(argument-matchers))
0040 //       .With(multi-argument-matcher)
0041 //       .WillByDefault(action);
0042 //
0043 //  where the .With() clause is optional.
0044 //
0045 // A user can use the EXPECT_CALL() macro to specify an expectation on
0046 // a mock method.  The syntax is:
0047 //
0048 //   EXPECT_CALL(mock_object, Method(argument-matchers))
0049 //       .With(multi-argument-matchers)
0050 //       .Times(cardinality)
0051 //       .InSequence(sequences)
0052 //       .After(expectations)
0053 //       .WillOnce(action)
0054 //       .WillRepeatedly(action)
0055 //       .RetiresOnSaturation();
0056 //
0057 // where all clauses are optional, and .InSequence()/.After()/
0058 // .WillOnce() can appear any number of times.
0059 
0060 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
0061 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
0062 
0063 #include <map>
0064 #include <set>
0065 #include <sstream>
0066 #include <string>
0067 #include <vector>
0068 
0069 #if GTEST_HAS_EXCEPTIONS
0070 # include <stdexcept>  // NOLINT
0071 #endif
0072 
0073 #include "gmock/gmock-actions.h"
0074 #include "gmock/gmock-cardinalities.h"
0075 #include "gmock/gmock-matchers.h"
0076 #include "gmock/internal/gmock-internal-utils.h"
0077 #include "gmock/internal/gmock-port.h"
0078 #include "gtest/gtest.h"
0079 
0080 namespace testing {
0081 
0082 // An abstract handle of an expectation.
0083 class Expectation;
0084 
0085 // A set of expectation handles.
0086 class ExpectationSet;
0087 
0088 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
0089 // and MUST NOT BE USED IN USER CODE!!!
0090 namespace internal {
0091 
0092 // Implements a mock function.
0093 template <typename F> class FunctionMocker;
0094 
0095 // Base class for expectations.
0096 class ExpectationBase;
0097 
0098 // Implements an expectation.
0099 template <typename F> class TypedExpectation;
0100 
0101 // Helper class for testing the Expectation class template.
0102 class ExpectationTester;
0103 
0104 // Base class for function mockers.
0105 template <typename F> class FunctionMockerBase;
0106 
0107 // Protects the mock object registry (in class Mock), all function
0108 // mockers, and all expectations.
0109 //
0110 // The reason we don't use more fine-grained protection is: when a
0111 // mock function Foo() is called, it needs to consult its expectations
0112 // to see which one should be picked.  If another thread is allowed to
0113 // call a mock function (either Foo() or a different one) at the same
0114 // time, it could affect the "retired" attributes of Foo()'s
0115 // expectations when InSequence() is used, and thus affect which
0116 // expectation gets picked.  Therefore, we sequence all mock function
0117 // calls to ensure the integrity of the mock objects' states.
0118 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
0119 
0120 // Untyped base class for ActionResultHolder<R>.
0121 class UntypedActionResultHolderBase;
0122 
0123 // Abstract base class of FunctionMockerBase.  This is the
0124 // type-agnostic part of the function mocker interface.  Its pure
0125 // virtual methods are implemented by FunctionMockerBase.
0126 class GTEST_API_ UntypedFunctionMockerBase {
0127  public:
0128   UntypedFunctionMockerBase();
0129   virtual ~UntypedFunctionMockerBase();
0130 
0131   // Verifies that all expectations on this mock function have been
0132   // satisfied.  Reports one or more Google Test non-fatal failures
0133   // and returns false if not.
0134   bool VerifyAndClearExpectationsLocked()
0135       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0136 
0137   // Clears the ON_CALL()s set on this mock function.
0138   virtual void ClearDefaultActionsLocked()
0139       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
0140 
0141   // In all of the following Untyped* functions, it's the caller's
0142   // responsibility to guarantee the correctness of the arguments'
0143   // types.
0144 
0145   // Performs the default action with the given arguments and returns
0146   // the action's result.  The call description string will be used in
0147   // the error message to describe the call in the case the default
0148   // action fails.
0149   // L = *
0150   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
0151       const void* untyped_args,
0152       const string& call_description) const = 0;
0153 
0154   // Performs the given action with the given arguments and returns
0155   // the action's result.
0156   // L = *
0157   virtual UntypedActionResultHolderBase* UntypedPerformAction(
0158       const void* untyped_action,
0159       const void* untyped_args) const = 0;
0160 
0161   // Writes a message that the call is uninteresting (i.e. neither
0162   // explicitly expected nor explicitly unexpected) to the given
0163   // ostream.
0164   virtual void UntypedDescribeUninterestingCall(
0165       const void* untyped_args,
0166       ::std::ostream* os) const
0167           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
0168 
0169   // Returns the expectation that matches the given function arguments
0170   // (or NULL is there's no match); when a match is found,
0171   // untyped_action is set to point to the action that should be
0172   // performed (or NULL if the action is "do default"), and
0173   // is_excessive is modified to indicate whether the call exceeds the
0174   // expected number.
0175   virtual const ExpectationBase* UntypedFindMatchingExpectation(
0176       const void* untyped_args,
0177       const void** untyped_action, bool* is_excessive,
0178       ::std::ostream* what, ::std::ostream* why)
0179           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
0180 
0181   // Prints the given function arguments to the ostream.
0182   virtual void UntypedPrintArgs(const void* untyped_args,
0183                                 ::std::ostream* os) const = 0;
0184 
0185   // Sets the mock object this mock method belongs to, and registers
0186   // this information in the global mock registry.  Will be called
0187   // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
0188   // method.
0189   // TODO(wan@google.com): rename to SetAndRegisterOwner().
0190   void RegisterOwner(const void* mock_obj)
0191       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0192 
0193   // Sets the mock object this mock method belongs to, and sets the
0194   // name of the mock function.  Will be called upon each invocation
0195   // of this mock function.
0196   void SetOwnerAndName(const void* mock_obj, const char* name)
0197       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0198 
0199   // Returns the mock object this mock method belongs to.  Must be
0200   // called after RegisterOwner() or SetOwnerAndName() has been
0201   // called.
0202   const void* MockObject() const
0203       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0204 
0205   // Returns the name of this mock method.  Must be called after
0206   // SetOwnerAndName() has been called.
0207   const char* Name() const
0208       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0209 
0210   // Returns the result of invoking this mock function with the given
0211   // arguments.  This function can be safely called from multiple
0212   // threads concurrently.  The caller is responsible for deleting the
0213   // result.
0214   UntypedActionResultHolderBase* UntypedInvokeWith(
0215       const void* untyped_args)
0216           GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0217 
0218  protected:
0219   typedef std::vector<const void*> UntypedOnCallSpecs;
0220 
0221   typedef std::vector<internal::linked_ptr<ExpectationBase> >
0222   UntypedExpectations;
0223 
0224   // Returns an Expectation object that references and co-owns exp,
0225   // which must be an expectation on this mock function.
0226   Expectation GetHandleOf(ExpectationBase* exp);
0227 
0228   // Address of the mock object this mock method belongs to.  Only
0229   // valid after this mock method has been called or
0230   // ON_CALL/EXPECT_CALL has been invoked on it.
0231   const void* mock_obj_;  // Protected by g_gmock_mutex.
0232 
0233   // Name of the function being mocked.  Only valid after this mock
0234   // method has been called.
0235   const char* name_;  // Protected by g_gmock_mutex.
0236 
0237   // All default action specs for this function mocker.
0238   UntypedOnCallSpecs untyped_on_call_specs_;
0239 
0240   // All expectations for this function mocker.
0241   UntypedExpectations untyped_expectations_;
0242 };  // class UntypedFunctionMockerBase
0243 
0244 // Untyped base class for OnCallSpec<F>.
0245 class UntypedOnCallSpecBase {
0246  public:
0247   // The arguments are the location of the ON_CALL() statement.
0248   UntypedOnCallSpecBase(const char* a_file, int a_line)
0249       : file_(a_file), line_(a_line), last_clause_(kNone) {}
0250 
0251   // Where in the source file was the default action spec defined?
0252   const char* file() const { return file_; }
0253   int line() const { return line_; }
0254 
0255  protected:
0256   // Gives each clause in the ON_CALL() statement a name.
0257   enum Clause {
0258     // Do not change the order of the enum members!  The run-time
0259     // syntax checking relies on it.
0260     kNone,
0261     kWith,
0262     kWillByDefault
0263   };
0264 
0265   // Asserts that the ON_CALL() statement has a certain property.
0266   void AssertSpecProperty(bool property, const string& failure_message) const {
0267     Assert(property, file_, line_, failure_message);
0268   }
0269 
0270   // Expects that the ON_CALL() statement has a certain property.
0271   void ExpectSpecProperty(bool property, const string& failure_message) const {
0272     Expect(property, file_, line_, failure_message);
0273   }
0274 
0275   const char* file_;
0276   int line_;
0277 
0278   // The last clause in the ON_CALL() statement as seen so far.
0279   // Initially kNone and changes as the statement is parsed.
0280   Clause last_clause_;
0281 };  // class UntypedOnCallSpecBase
0282 
0283 // This template class implements an ON_CALL spec.
0284 template <typename F>
0285 class OnCallSpec : public UntypedOnCallSpecBase {
0286  public:
0287   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
0288   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
0289 
0290   // Constructs an OnCallSpec object from the information inside
0291   // the parenthesis of an ON_CALL() statement.
0292   OnCallSpec(const char* a_file, int a_line,
0293              const ArgumentMatcherTuple& matchers)
0294       : UntypedOnCallSpecBase(a_file, a_line),
0295         matchers_(matchers),
0296         // By default, extra_matcher_ should match anything.  However,
0297         // we cannot initialize it with _ as that triggers a compiler
0298         // bug in Symbian's C++ compiler (cannot decide between two
0299         // overloaded constructors of Matcher<const ArgumentTuple&>).
0300         extra_matcher_(A<const ArgumentTuple&>()) {
0301   }
0302 
0303   // Implements the .With() clause.
0304   OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
0305     // Makes sure this is called at most once.
0306     ExpectSpecProperty(last_clause_ < kWith,
0307                        ".With() cannot appear "
0308                        "more than once in an ON_CALL().");
0309     last_clause_ = kWith;
0310 
0311     extra_matcher_ = m;
0312     return *this;
0313   }
0314 
0315   // Implements the .WillByDefault() clause.
0316   OnCallSpec& WillByDefault(const Action<F>& action) {
0317     ExpectSpecProperty(last_clause_ < kWillByDefault,
0318                        ".WillByDefault() must appear "
0319                        "exactly once in an ON_CALL().");
0320     last_clause_ = kWillByDefault;
0321 
0322     ExpectSpecProperty(!action.IsDoDefault(),
0323                        "DoDefault() cannot be used in ON_CALL().");
0324     action_ = action;
0325     return *this;
0326   }
0327 
0328   // Returns true iff the given arguments match the matchers.
0329   bool Matches(const ArgumentTuple& args) const {
0330     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
0331   }
0332 
0333   // Returns the action specified by the user.
0334   const Action<F>& GetAction() const {
0335     AssertSpecProperty(last_clause_ == kWillByDefault,
0336                        ".WillByDefault() must appear exactly "
0337                        "once in an ON_CALL().");
0338     return action_;
0339   }
0340 
0341  private:
0342   // The information in statement
0343   //
0344   //   ON_CALL(mock_object, Method(matchers))
0345   //       .With(multi-argument-matcher)
0346   //       .WillByDefault(action);
0347   //
0348   // is recorded in the data members like this:
0349   //
0350   //   source file that contains the statement => file_
0351   //   line number of the statement            => line_
0352   //   matchers                                => matchers_
0353   //   multi-argument-matcher                  => extra_matcher_
0354   //   action                                  => action_
0355   ArgumentMatcherTuple matchers_;
0356   Matcher<const ArgumentTuple&> extra_matcher_;
0357   Action<F> action_;
0358 };  // class OnCallSpec
0359 
0360 // Possible reactions on uninteresting calls.
0361 enum CallReaction {
0362   kAllow,
0363   kWarn,
0364   kFail,
0365   kDefault = kWarn  // By default, warn about uninteresting calls.
0366 };
0367 
0368 }  // namespace internal
0369 
0370 // Utilities for manipulating mock objects.
0371 class GTEST_API_ Mock {
0372  public:
0373   // The following public methods can be called concurrently.
0374 
0375   // Tells Google Mock to ignore mock_obj when checking for leaked
0376   // mock objects.
0377   static void AllowLeak(const void* mock_obj)
0378       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0379 
0380   // Verifies and clears all expectations on the given mock object.
0381   // If the expectations aren't satisfied, generates one or more
0382   // Google Test non-fatal failures and returns false.
0383   static bool VerifyAndClearExpectations(void* mock_obj)
0384       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0385 
0386   // Verifies all expectations on the given mock object and clears its
0387   // default actions and expectations.  Returns true iff the
0388   // verification was successful.
0389   static bool VerifyAndClear(void* mock_obj)
0390       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0391 
0392  private:
0393   friend class internal::UntypedFunctionMockerBase;
0394 
0395   // Needed for a function mocker to register itself (so that we know
0396   // how to clear a mock object).
0397   template <typename F>
0398   friend class internal::FunctionMockerBase;
0399 
0400   template <typename M>
0401   friend class NiceMock;
0402 
0403   template <typename M>
0404   friend class NaggyMock;
0405 
0406   template <typename M>
0407   friend class StrictMock;
0408 
0409   // Tells Google Mock to allow uninteresting calls on the given mock
0410   // object.
0411   static void AllowUninterestingCalls(const void* mock_obj)
0412       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0413 
0414   // Tells Google Mock to warn the user about uninteresting calls on
0415   // the given mock object.
0416   static void WarnUninterestingCalls(const void* mock_obj)
0417       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0418 
0419   // Tells Google Mock to fail uninteresting calls on the given mock
0420   // object.
0421   static void FailUninterestingCalls(const void* mock_obj)
0422       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0423 
0424   // Tells Google Mock the given mock object is being destroyed and
0425   // its entry in the call-reaction table should be removed.
0426   static void UnregisterCallReaction(const void* mock_obj)
0427       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0428 
0429   // Returns the reaction Google Mock will have on uninteresting calls
0430   // made on the given mock object.
0431   static internal::CallReaction GetReactionOnUninterestingCalls(
0432       const void* mock_obj)
0433           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0434 
0435   // Verifies that all expectations on the given mock object have been
0436   // satisfied.  Reports one or more Google Test non-fatal failures
0437   // and returns false if not.
0438   static bool VerifyAndClearExpectationsLocked(void* mock_obj)
0439       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0440 
0441   // Clears all ON_CALL()s set on the given mock object.
0442   static void ClearDefaultActionsLocked(void* mock_obj)
0443       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0444 
0445   // Registers a mock object and a mock method it owns.
0446   static void Register(
0447       const void* mock_obj,
0448       internal::UntypedFunctionMockerBase* mocker)
0449           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0450 
0451   // Tells Google Mock where in the source code mock_obj is used in an
0452   // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
0453   // information helps the user identify which object it is.
0454   static void RegisterUseByOnCallOrExpectCall(
0455       const void* mock_obj, const char* file, int line)
0456           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0457 
0458   // Unregisters a mock method; removes the owning mock object from
0459   // the registry when the last mock method associated with it has
0460   // been unregistered.  This is called only in the destructor of
0461   // FunctionMockerBase.
0462   static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
0463       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0464 };  // class Mock
0465 
0466 // An abstract handle of an expectation.  Useful in the .After()
0467 // clause of EXPECT_CALL() for setting the (partial) order of
0468 // expectations.  The syntax:
0469 //
0470 //   Expectation e1 = EXPECT_CALL(...)...;
0471 //   EXPECT_CALL(...).After(e1)...;
0472 //
0473 // sets two expectations where the latter can only be matched after
0474 // the former has been satisfied.
0475 //
0476 // Notes:
0477 //   - This class is copyable and has value semantics.
0478 //   - Constness is shallow: a const Expectation object itself cannot
0479 //     be modified, but the mutable methods of the ExpectationBase
0480 //     object it references can be called via expectation_base().
0481 //   - The constructors and destructor are defined out-of-line because
0482 //     the Symbian WINSCW compiler wants to otherwise instantiate them
0483 //     when it sees this class definition, at which point it doesn't have
0484 //     ExpectationBase available yet, leading to incorrect destruction
0485 //     in the linked_ptr (or compilation errors if using a checking
0486 //     linked_ptr).
0487 class GTEST_API_ Expectation {
0488  public:
0489   // Constructs a null object that doesn't reference any expectation.
0490   Expectation();
0491 
0492   ~Expectation();
0493 
0494   // This single-argument ctor must not be explicit, in order to support the
0495   //   Expectation e = EXPECT_CALL(...);
0496   // syntax.
0497   //
0498   // A TypedExpectation object stores its pre-requisites as
0499   // Expectation objects, and needs to call the non-const Retire()
0500   // method on the ExpectationBase objects they reference.  Therefore
0501   // Expectation must receive a *non-const* reference to the
0502   // ExpectationBase object.
0503   Expectation(internal::ExpectationBase& exp);  // NOLINT
0504 
0505   // The compiler-generated copy ctor and operator= work exactly as
0506   // intended, so we don't need to define our own.
0507 
0508   // Returns true iff rhs references the same expectation as this object does.
0509   bool operator==(const Expectation& rhs) const {
0510     return expectation_base_ == rhs.expectation_base_;
0511   }
0512 
0513   bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
0514 
0515  private:
0516   friend class ExpectationSet;
0517   friend class Sequence;
0518   friend class ::testing::internal::ExpectationBase;
0519   friend class ::testing::internal::UntypedFunctionMockerBase;
0520 
0521   template <typename F>
0522   friend class ::testing::internal::FunctionMockerBase;
0523 
0524   template <typename F>
0525   friend class ::testing::internal::TypedExpectation;
0526 
0527   // This comparator is needed for putting Expectation objects into a set.
0528   class Less {
0529    public:
0530     bool operator()(const Expectation& lhs, const Expectation& rhs) const {
0531       return lhs.expectation_base_.get() < rhs.expectation_base_.get();
0532     }
0533   };
0534 
0535   typedef ::std::set<Expectation, Less> Set;
0536 
0537   Expectation(
0538       const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
0539 
0540   // Returns the expectation this object references.
0541   const internal::linked_ptr<internal::ExpectationBase>&
0542   expectation_base() const {
0543     return expectation_base_;
0544   }
0545 
0546   // A linked_ptr that co-owns the expectation this handle references.
0547   internal::linked_ptr<internal::ExpectationBase> expectation_base_;
0548 };
0549 
0550 // A set of expectation handles.  Useful in the .After() clause of
0551 // EXPECT_CALL() for setting the (partial) order of expectations.  The
0552 // syntax:
0553 //
0554 //   ExpectationSet es;
0555 //   es += EXPECT_CALL(...)...;
0556 //   es += EXPECT_CALL(...)...;
0557 //   EXPECT_CALL(...).After(es)...;
0558 //
0559 // sets three expectations where the last one can only be matched
0560 // after the first two have both been satisfied.
0561 //
0562 // This class is copyable and has value semantics.
0563 class ExpectationSet {
0564  public:
0565   // A bidirectional iterator that can read a const element in the set.
0566   typedef Expectation::Set::const_iterator const_iterator;
0567 
0568   // An object stored in the set.  This is an alias of Expectation.
0569   typedef Expectation::Set::value_type value_type;
0570 
0571   // Constructs an empty set.
0572   ExpectationSet() {}
0573 
0574   // This single-argument ctor must not be explicit, in order to support the
0575   //   ExpectationSet es = EXPECT_CALL(...);
0576   // syntax.
0577   ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
0578     *this += Expectation(exp);
0579   }
0580 
0581   // This single-argument ctor implements implicit conversion from
0582   // Expectation and thus must not be explicit.  This allows either an
0583   // Expectation or an ExpectationSet to be used in .After().
0584   ExpectationSet(const Expectation& e) {  // NOLINT
0585     *this += e;
0586   }
0587 
0588   // The compiler-generator ctor and operator= works exactly as
0589   // intended, so we don't need to define our own.
0590 
0591   // Returns true iff rhs contains the same set of Expectation objects
0592   // as this does.
0593   bool operator==(const ExpectationSet& rhs) const {
0594     return expectations_ == rhs.expectations_;
0595   }
0596 
0597   bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
0598 
0599   // Implements the syntax
0600   //   expectation_set += EXPECT_CALL(...);
0601   ExpectationSet& operator+=(const Expectation& e) {
0602     expectations_.insert(e);
0603     return *this;
0604   }
0605 
0606   int size() const { return static_cast<int>(expectations_.size()); }
0607 
0608   const_iterator begin() const { return expectations_.begin(); }
0609   const_iterator end() const { return expectations_.end(); }
0610 
0611  private:
0612   Expectation::Set expectations_;
0613 };
0614 
0615 
0616 // Sequence objects are used by a user to specify the relative order
0617 // in which the expectations should match.  They are copyable (we rely
0618 // on the compiler-defined copy constructor and assignment operator).
0619 class GTEST_API_ Sequence {
0620  public:
0621   // Constructs an empty sequence.
0622   Sequence() : last_expectation_(new Expectation) {}
0623 
0624   // Adds an expectation to this sequence.  The caller must ensure
0625   // that no other thread is accessing this Sequence object.
0626   void AddExpectation(const Expectation& expectation) const;
0627 
0628  private:
0629   // The last expectation in this sequence.  We use a linked_ptr here
0630   // because Sequence objects are copyable and we want the copies to
0631   // be aliases.  The linked_ptr allows the copies to co-own and share
0632   // the same Expectation object.
0633   internal::linked_ptr<Expectation> last_expectation_;
0634 };  // class Sequence
0635 
0636 // An object of this type causes all EXPECT_CALL() statements
0637 // encountered in its scope to be put in an anonymous sequence.  The
0638 // work is done in the constructor and destructor.  You should only
0639 // create an InSequence object on the stack.
0640 //
0641 // The sole purpose for this class is to support easy definition of
0642 // sequential expectations, e.g.
0643 //
0644 //   {
0645 //     InSequence dummy;  // The name of the object doesn't matter.
0646 //
0647 //     // The following expectations must match in the order they appear.
0648 //     EXPECT_CALL(a, Bar())...;
0649 //     EXPECT_CALL(a, Baz())...;
0650 //     ...
0651 //     EXPECT_CALL(b, Xyz())...;
0652 //   }
0653 //
0654 // You can create InSequence objects in multiple threads, as long as
0655 // they are used to affect different mock objects.  The idea is that
0656 // each thread can create and set up its own mocks as if it's the only
0657 // thread.  However, for clarity of your tests we recommend you to set
0658 // up mocks in the main thread unless you have a good reason not to do
0659 // so.
0660 class GTEST_API_ InSequence {
0661  public:
0662   InSequence();
0663   ~InSequence();
0664  private:
0665   bool sequence_created_;
0666 
0667   GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
0668 } GTEST_ATTRIBUTE_UNUSED_;
0669 
0670 namespace internal {
0671 
0672 // Points to the implicit sequence introduced by a living InSequence
0673 // object (if any) in the current thread or NULL.
0674 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
0675 
0676 // Base class for implementing expectations.
0677 //
0678 // There are two reasons for having a type-agnostic base class for
0679 // Expectation:
0680 //
0681 //   1. We need to store collections of expectations of different
0682 //   types (e.g. all pre-requisites of a particular expectation, all
0683 //   expectations in a sequence).  Therefore these expectation objects
0684 //   must share a common base class.
0685 //
0686 //   2. We can avoid binary code bloat by moving methods not depending
0687 //   on the template argument of Expectation to the base class.
0688 //
0689 // This class is internal and mustn't be used by user code directly.
0690 class GTEST_API_ ExpectationBase {
0691  public:
0692   // source_text is the EXPECT_CALL(...) source that created this Expectation.
0693   ExpectationBase(const char* file, int line, const string& source_text);
0694 
0695   virtual ~ExpectationBase();
0696 
0697   // Where in the source file was the expectation spec defined?
0698   const char* file() const { return file_; }
0699   int line() const { return line_; }
0700   const char* source_text() const { return source_text_.c_str(); }
0701   // Returns the cardinality specified in the expectation spec.
0702   const Cardinality& cardinality() const { return cardinality_; }
0703 
0704   // Describes the source file location of this expectation.
0705   void DescribeLocationTo(::std::ostream* os) const {
0706     *os << FormatFileLocation(file(), line()) << " ";
0707   }
0708 
0709   // Describes how many times a function call matching this
0710   // expectation has occurred.
0711   void DescribeCallCountTo(::std::ostream* os) const
0712       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0713 
0714   // If this mock method has an extra matcher (i.e. .With(matcher)),
0715   // describes it to the ostream.
0716   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
0717 
0718  protected:
0719   friend class ::testing::Expectation;
0720   friend class UntypedFunctionMockerBase;
0721 
0722   enum Clause {
0723     // Don't change the order of the enum members!
0724     kNone,
0725     kWith,
0726     kTimes,
0727     kInSequence,
0728     kAfter,
0729     kWillOnce,
0730     kWillRepeatedly,
0731     kRetiresOnSaturation
0732   };
0733 
0734   typedef std::vector<const void*> UntypedActions;
0735 
0736   // Returns an Expectation object that references and co-owns this
0737   // expectation.
0738   virtual Expectation GetHandle() = 0;
0739 
0740   // Asserts that the EXPECT_CALL() statement has the given property.
0741   void AssertSpecProperty(bool property, const string& failure_message) const {
0742     Assert(property, file_, line_, failure_message);
0743   }
0744 
0745   // Expects that the EXPECT_CALL() statement has the given property.
0746   void ExpectSpecProperty(bool property, const string& failure_message) const {
0747     Expect(property, file_, line_, failure_message);
0748   }
0749 
0750   // Explicitly specifies the cardinality of this expectation.  Used
0751   // by the subclasses to implement the .Times() clause.
0752   void SpecifyCardinality(const Cardinality& cardinality);
0753 
0754   // Returns true iff the user specified the cardinality explicitly
0755   // using a .Times().
0756   bool cardinality_specified() const { return cardinality_specified_; }
0757 
0758   // Sets the cardinality of this expectation spec.
0759   void set_cardinality(const Cardinality& a_cardinality) {
0760     cardinality_ = a_cardinality;
0761   }
0762 
0763   // The following group of methods should only be called after the
0764   // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
0765   // the current thread.
0766 
0767   // Retires all pre-requisites of this expectation.
0768   void RetireAllPreRequisites()
0769       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0770 
0771   // Returns true iff this expectation is retired.
0772   bool is_retired() const
0773       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0774     g_gmock_mutex.AssertHeld();
0775     return retired_;
0776   }
0777 
0778   // Retires this expectation.
0779   void Retire()
0780       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0781     g_gmock_mutex.AssertHeld();
0782     retired_ = true;
0783   }
0784 
0785   // Returns true iff this expectation is satisfied.
0786   bool IsSatisfied() const
0787       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0788     g_gmock_mutex.AssertHeld();
0789     return cardinality().IsSatisfiedByCallCount(call_count_);
0790   }
0791 
0792   // Returns true iff this expectation is saturated.
0793   bool IsSaturated() const
0794       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0795     g_gmock_mutex.AssertHeld();
0796     return cardinality().IsSaturatedByCallCount(call_count_);
0797   }
0798 
0799   // Returns true iff this expectation is over-saturated.
0800   bool IsOverSaturated() const
0801       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0802     g_gmock_mutex.AssertHeld();
0803     return cardinality().IsOverSaturatedByCallCount(call_count_);
0804   }
0805 
0806   // Returns true iff all pre-requisites of this expectation are satisfied.
0807   bool AllPrerequisitesAreSatisfied() const
0808       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0809 
0810   // Adds unsatisfied pre-requisites of this expectation to 'result'.
0811   void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
0812       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0813 
0814   // Returns the number this expectation has been invoked.
0815   int call_count() const
0816       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0817     g_gmock_mutex.AssertHeld();
0818     return call_count_;
0819   }
0820 
0821   // Increments the number this expectation has been invoked.
0822   void IncrementCallCount()
0823       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0824     g_gmock_mutex.AssertHeld();
0825     call_count_++;
0826   }
0827 
0828   // Checks the action count (i.e. the number of WillOnce() and
0829   // WillRepeatedly() clauses) against the cardinality if this hasn't
0830   // been done before.  Prints a warning if there are too many or too
0831   // few actions.
0832   void CheckActionCountIfNotDone() const
0833       GTEST_LOCK_EXCLUDED_(mutex_);
0834 
0835   friend class ::testing::Sequence;
0836   friend class ::testing::internal::ExpectationTester;
0837 
0838   template <typename Function>
0839   friend class TypedExpectation;
0840 
0841   // Implements the .Times() clause.
0842   void UntypedTimes(const Cardinality& a_cardinality);
0843 
0844   // This group of fields are part of the spec and won't change after
0845   // an EXPECT_CALL() statement finishes.
0846   const char* file_;          // The file that contains the expectation.
0847   int line_;                  // The line number of the expectation.
0848   const string source_text_;  // The EXPECT_CALL(...) source text.
0849   // True iff the cardinality is specified explicitly.
0850   bool cardinality_specified_;
0851   Cardinality cardinality_;            // The cardinality of the expectation.
0852   // The immediate pre-requisites (i.e. expectations that must be
0853   // satisfied before this expectation can be matched) of this
0854   // expectation.  We use linked_ptr in the set because we want an
0855   // Expectation object to be co-owned by its FunctionMocker and its
0856   // successors.  This allows multiple mock objects to be deleted at
0857   // different times.
0858   ExpectationSet immediate_prerequisites_;
0859 
0860   // This group of fields are the current state of the expectation,
0861   // and can change as the mock function is called.
0862   int call_count_;  // How many times this expectation has been invoked.
0863   bool retired_;    // True iff this expectation has retired.
0864   UntypedActions untyped_actions_;
0865   bool extra_matcher_specified_;
0866   bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
0867   bool retires_on_saturation_;
0868   Clause last_clause_;
0869   mutable bool action_count_checked_;  // Under mutex_.
0870   mutable Mutex mutex_;  // Protects action_count_checked_.
0871 
0872   GTEST_DISALLOW_ASSIGN_(ExpectationBase);
0873 };  // class ExpectationBase
0874 
0875 // Impements an expectation for the given function type.
0876 template <typename F>
0877 class TypedExpectation : public ExpectationBase {
0878  public:
0879   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
0880   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
0881   typedef typename Function<F>::Result Result;
0882 
0883   TypedExpectation(FunctionMockerBase<F>* owner,
0884                    const char* a_file, int a_line, const string& a_source_text,
0885                    const ArgumentMatcherTuple& m)
0886       : ExpectationBase(a_file, a_line, a_source_text),
0887         owner_(owner),
0888         matchers_(m),
0889         // By default, extra_matcher_ should match anything.  However,
0890         // we cannot initialize it with _ as that triggers a compiler
0891         // bug in Symbian's C++ compiler (cannot decide between two
0892         // overloaded constructors of Matcher<const ArgumentTuple&>).
0893         extra_matcher_(A<const ArgumentTuple&>()),
0894         repeated_action_(DoDefault()) {}
0895 
0896   virtual ~TypedExpectation() {
0897     // Check the validity of the action count if it hasn't been done
0898     // yet (for example, if the expectation was never used).
0899     CheckActionCountIfNotDone();
0900     for (UntypedActions::const_iterator it = untyped_actions_.begin();
0901          it != untyped_actions_.end(); ++it) {
0902       delete static_cast<const Action<F>*>(*it);
0903     }
0904   }
0905 
0906   // Implements the .With() clause.
0907   TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
0908     if (last_clause_ == kWith) {
0909       ExpectSpecProperty(false,
0910                          ".With() cannot appear "
0911                          "more than once in an EXPECT_CALL().");
0912     } else {
0913       ExpectSpecProperty(last_clause_ < kWith,
0914                          ".With() must be the first "
0915                          "clause in an EXPECT_CALL().");
0916     }
0917     last_clause_ = kWith;
0918 
0919     extra_matcher_ = m;
0920     extra_matcher_specified_ = true;
0921     return *this;
0922   }
0923 
0924   // Implements the .Times() clause.
0925   TypedExpectation& Times(const Cardinality& a_cardinality) {
0926     ExpectationBase::UntypedTimes(a_cardinality);
0927     return *this;
0928   }
0929 
0930   // Implements the .Times() clause.
0931   TypedExpectation& Times(int n) {
0932     return Times(Exactly(n));
0933   }
0934 
0935   // Implements the .InSequence() clause.
0936   TypedExpectation& InSequence(const Sequence& s) {
0937     ExpectSpecProperty(last_clause_ <= kInSequence,
0938                        ".InSequence() cannot appear after .After(),"
0939                        " .WillOnce(), .WillRepeatedly(), or "
0940                        ".RetiresOnSaturation().");
0941     last_clause_ = kInSequence;
0942 
0943     s.AddExpectation(GetHandle());
0944     return *this;
0945   }
0946   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
0947     return InSequence(s1).InSequence(s2);
0948   }
0949   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0950                                const Sequence& s3) {
0951     return InSequence(s1, s2).InSequence(s3);
0952   }
0953   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0954                                const Sequence& s3, const Sequence& s4) {
0955     return InSequence(s1, s2, s3).InSequence(s4);
0956   }
0957   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0958                                const Sequence& s3, const Sequence& s4,
0959                                const Sequence& s5) {
0960     return InSequence(s1, s2, s3, s4).InSequence(s5);
0961   }
0962 
0963   // Implements that .After() clause.
0964   TypedExpectation& After(const ExpectationSet& s) {
0965     ExpectSpecProperty(last_clause_ <= kAfter,
0966                        ".After() cannot appear after .WillOnce(),"
0967                        " .WillRepeatedly(), or "
0968                        ".RetiresOnSaturation().");
0969     last_clause_ = kAfter;
0970 
0971     for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
0972       immediate_prerequisites_ += *it;
0973     }
0974     return *this;
0975   }
0976   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
0977     return After(s1).After(s2);
0978   }
0979   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0980                           const ExpectationSet& s3) {
0981     return After(s1, s2).After(s3);
0982   }
0983   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0984                           const ExpectationSet& s3, const ExpectationSet& s4) {
0985     return After(s1, s2, s3).After(s4);
0986   }
0987   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0988                           const ExpectationSet& s3, const ExpectationSet& s4,
0989                           const ExpectationSet& s5) {
0990     return After(s1, s2, s3, s4).After(s5);
0991   }
0992 
0993   // Implements the .WillOnce() clause.
0994   TypedExpectation& WillOnce(const Action<F>& action) {
0995     ExpectSpecProperty(last_clause_ <= kWillOnce,
0996                        ".WillOnce() cannot appear after "
0997                        ".WillRepeatedly() or .RetiresOnSaturation().");
0998     last_clause_ = kWillOnce;
0999 
1000     untyped_actions_.push_back(new Action<F>(action));
1001     if (!cardinality_specified()) {
1002       set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1003     }
1004     return *this;
1005   }
1006 
1007   // Implements the .WillRepeatedly() clause.
1008   TypedExpectation& WillRepeatedly(const Action<F>& action) {
1009     if (last_clause_ == kWillRepeatedly) {
1010       ExpectSpecProperty(false,
1011                          ".WillRepeatedly() cannot appear "
1012                          "more than once in an EXPECT_CALL().");
1013     } else {
1014       ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1015                          ".WillRepeatedly() cannot appear "
1016                          "after .RetiresOnSaturation().");
1017     }
1018     last_clause_ = kWillRepeatedly;
1019     repeated_action_specified_ = true;
1020 
1021     repeated_action_ = action;
1022     if (!cardinality_specified()) {
1023       set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1024     }
1025 
1026     // Now that no more action clauses can be specified, we check
1027     // whether their count makes sense.
1028     CheckActionCountIfNotDone();
1029     return *this;
1030   }
1031 
1032   // Implements the .RetiresOnSaturation() clause.
1033   TypedExpectation& RetiresOnSaturation() {
1034     ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1035                        ".RetiresOnSaturation() cannot appear "
1036                        "more than once.");
1037     last_clause_ = kRetiresOnSaturation;
1038     retires_on_saturation_ = true;
1039 
1040     // Now that no more action clauses can be specified, we check
1041     // whether their count makes sense.
1042     CheckActionCountIfNotDone();
1043     return *this;
1044   }
1045 
1046   // Returns the matchers for the arguments as specified inside the
1047   // EXPECT_CALL() macro.
1048   const ArgumentMatcherTuple& matchers() const {
1049     return matchers_;
1050   }
1051 
1052   // Returns the matcher specified by the .With() clause.
1053   const Matcher<const ArgumentTuple&>& extra_matcher() const {
1054     return extra_matcher_;
1055   }
1056 
1057   // Returns the action specified by the .WillRepeatedly() clause.
1058   const Action<F>& repeated_action() const { return repeated_action_; }
1059 
1060   // If this mock method has an extra matcher (i.e. .With(matcher)),
1061   // describes it to the ostream.
1062   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
1063     if (extra_matcher_specified_) {
1064       *os << "    Expected args: ";
1065       extra_matcher_.DescribeTo(os);
1066       *os << "\n";
1067     }
1068   }
1069 
1070  private:
1071   template <typename Function>
1072   friend class FunctionMockerBase;
1073 
1074   // Returns an Expectation object that references and co-owns this
1075   // expectation.
1076   virtual Expectation GetHandle() {
1077     return owner_->GetHandleOf(this);
1078   }
1079 
1080   // The following methods will be called only after the EXPECT_CALL()
1081   // statement finishes and when the current thread holds
1082   // g_gmock_mutex.
1083 
1084   // Returns true iff this expectation matches the given arguments.
1085   bool Matches(const ArgumentTuple& args) const
1086       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1087     g_gmock_mutex.AssertHeld();
1088     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1089   }
1090 
1091   // Returns true iff this expectation should handle the given arguments.
1092   bool ShouldHandleArguments(const ArgumentTuple& args) const
1093       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1094     g_gmock_mutex.AssertHeld();
1095 
1096     // In case the action count wasn't checked when the expectation
1097     // was defined (e.g. if this expectation has no WillRepeatedly()
1098     // or RetiresOnSaturation() clause), we check it when the
1099     // expectation is used for the first time.
1100     CheckActionCountIfNotDone();
1101     return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1102   }
1103 
1104   // Describes the result of matching the arguments against this
1105   // expectation to the given ostream.
1106   void ExplainMatchResultTo(
1107       const ArgumentTuple& args,
1108       ::std::ostream* os) const
1109           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1110     g_gmock_mutex.AssertHeld();
1111 
1112     if (is_retired()) {
1113       *os << "         Expected: the expectation is active\n"
1114           << "           Actual: it is retired\n";
1115     } else if (!Matches(args)) {
1116       if (!TupleMatches(matchers_, args)) {
1117         ExplainMatchFailureTupleTo(matchers_, args, os);
1118       }
1119       StringMatchResultListener listener;
1120       if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1121         *os << "    Expected args: ";
1122         extra_matcher_.DescribeTo(os);
1123         *os << "\n           Actual: don't match";
1124 
1125         internal::PrintIfNotEmpty(listener.str(), os);
1126         *os << "\n";
1127       }
1128     } else if (!AllPrerequisitesAreSatisfied()) {
1129       *os << "         Expected: all pre-requisites are satisfied\n"
1130           << "           Actual: the following immediate pre-requisites "
1131           << "are not satisfied:\n";
1132       ExpectationSet unsatisfied_prereqs;
1133       FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1134       int i = 0;
1135       for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1136            it != unsatisfied_prereqs.end(); ++it) {
1137         it->expectation_base()->DescribeLocationTo(os);
1138         *os << "pre-requisite #" << i++ << "\n";
1139       }
1140       *os << "                   (end of pre-requisites)\n";
1141     } else {
1142       // This line is here just for completeness' sake.  It will never
1143       // be executed as currently the ExplainMatchResultTo() function
1144       // is called only when the mock function call does NOT match the
1145       // expectation.
1146       *os << "The call matches the expectation.\n";
1147     }
1148   }
1149 
1150   // Returns the action that should be taken for the current invocation.
1151   const Action<F>& GetCurrentAction(
1152       const FunctionMockerBase<F>* mocker,
1153       const ArgumentTuple& args) const
1154           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1155     g_gmock_mutex.AssertHeld();
1156     const int count = call_count();
1157     Assert(count >= 1, __FILE__, __LINE__,
1158            "call_count() is <= 0 when GetCurrentAction() is "
1159            "called - this should never happen.");
1160 
1161     const int action_count = static_cast<int>(untyped_actions_.size());
1162     if (action_count > 0 && !repeated_action_specified_ &&
1163         count > action_count) {
1164       // If there is at least one WillOnce() and no WillRepeatedly(),
1165       // we warn the user when the WillOnce() clauses ran out.
1166       ::std::stringstream ss;
1167       DescribeLocationTo(&ss);
1168       ss << "Actions ran out in " << source_text() << "...\n"
1169          << "Called " << count << " times, but only "
1170          << action_count << " WillOnce()"
1171          << (action_count == 1 ? " is" : "s are") << " specified - ";
1172       mocker->DescribeDefaultActionTo(args, &ss);
1173       Log(kWarning, ss.str(), 1);
1174     }
1175 
1176     return count <= action_count ?
1177         *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1178         repeated_action();
1179   }
1180 
1181   // Given the arguments of a mock function call, if the call will
1182   // over-saturate this expectation, returns the default action;
1183   // otherwise, returns the next action in this expectation.  Also
1184   // describes *what* happened to 'what', and explains *why* Google
1185   // Mock does it to 'why'.  This method is not const as it calls
1186   // IncrementCallCount().  A return value of NULL means the default
1187   // action.
1188   const Action<F>* GetActionForArguments(
1189       const FunctionMockerBase<F>* mocker,
1190       const ArgumentTuple& args,
1191       ::std::ostream* what,
1192       ::std::ostream* why)
1193           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1194     g_gmock_mutex.AssertHeld();
1195     if (IsSaturated()) {
1196       // We have an excessive call.
1197       IncrementCallCount();
1198       *what << "Mock function called more times than expected - ";
1199       mocker->DescribeDefaultActionTo(args, what);
1200       DescribeCallCountTo(why);
1201 
1202       // TODO(wan@google.com): allow the user to control whether
1203       // unexpected calls should fail immediately or continue using a
1204       // flag --gmock_unexpected_calls_are_fatal.
1205       return NULL;
1206     }
1207 
1208     IncrementCallCount();
1209     RetireAllPreRequisites();
1210 
1211     if (retires_on_saturation_ && IsSaturated()) {
1212       Retire();
1213     }
1214 
1215     // Must be done after IncrementCount()!
1216     *what << "Mock function call matches " << source_text() <<"...\n";
1217     return &(GetCurrentAction(mocker, args));
1218   }
1219 
1220   // All the fields below won't change once the EXPECT_CALL()
1221   // statement finishes.
1222   FunctionMockerBase<F>* const owner_;
1223   ArgumentMatcherTuple matchers_;
1224   Matcher<const ArgumentTuple&> extra_matcher_;
1225   Action<F> repeated_action_;
1226 
1227   GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1228 };  // class TypedExpectation
1229 
1230 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1231 // specifying the default behavior of, or expectation on, a mock
1232 // function.
1233 
1234 // Note: class MockSpec really belongs to the ::testing namespace.
1235 // However if we define it in ::testing, MSVC will complain when
1236 // classes in ::testing::internal declare it as a friend class
1237 // template.  To workaround this compiler bug, we define MockSpec in
1238 // ::testing::internal and import it into ::testing.
1239 
1240 // Logs a message including file and line number information.
1241 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1242                                 const char* file, int line,
1243                                 const string& message);
1244 
1245 template <typename F>
1246 class MockSpec {
1247  public:
1248   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1249   typedef typename internal::Function<F>::ArgumentMatcherTuple
1250       ArgumentMatcherTuple;
1251 
1252   // Constructs a MockSpec object, given the function mocker object
1253   // that the spec is associated with.
1254   explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1255       : function_mocker_(function_mocker) {}
1256 
1257   // Adds a new default action spec to the function mocker and returns
1258   // the newly created spec.
1259   internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1260       const char* file, int line, const char* obj, const char* call) {
1261     LogWithLocation(internal::kInfo, file, line,
1262         string("ON_CALL(") + obj + ", " + call + ") invoked");
1263     return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1264   }
1265 
1266   // Adds a new expectation spec to the function mocker and returns
1267   // the newly created spec.
1268   internal::TypedExpectation<F>& InternalExpectedAt(
1269       const char* file, int line, const char* obj, const char* call) {
1270     const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
1271     LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1272     return function_mocker_->AddNewExpectation(
1273         file, line, source_text, matchers_);
1274   }
1275 
1276  private:
1277   template <typename Function>
1278   friend class internal::FunctionMocker;
1279 
1280   void SetMatchers(const ArgumentMatcherTuple& matchers) {
1281     matchers_ = matchers;
1282   }
1283 
1284   // The function mocker that owns this spec.
1285   internal::FunctionMockerBase<F>* const function_mocker_;
1286   // The argument matchers specified in the spec.
1287   ArgumentMatcherTuple matchers_;
1288 
1289   GTEST_DISALLOW_ASSIGN_(MockSpec);
1290 };  // class MockSpec
1291 
1292 // Wrapper type for generically holding an ordinary value or lvalue reference.
1293 // If T is not a reference type, it must be copyable or movable.
1294 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1295 // T is a move-only value type (which means that it will always be copyable
1296 // if the current platform does not support move semantics).
1297 //
1298 // The primary template defines handling for values, but function header
1299 // comments describe the contract for the whole template (including
1300 // specializations).
1301 template <typename T>
1302 class ReferenceOrValueWrapper {
1303  public:
1304   // Constructs a wrapper from the given value/reference.
1305   explicit ReferenceOrValueWrapper(T value)
1306       : value_(::testing::internal::move(value)) {
1307   }
1308 
1309   // Unwraps and returns the underlying value/reference, exactly as
1310   // originally passed. The behavior of calling this more than once on
1311   // the same object is unspecified.
1312   T Unwrap() { return ::testing::internal::move(value_); }
1313 
1314   // Provides nondestructive access to the underlying value/reference.
1315   // Always returns a const reference (more precisely,
1316   // const RemoveReference<T>&). The behavior of calling this after
1317   // calling Unwrap on the same object is unspecified.
1318   const T& Peek() const {
1319     return value_;
1320   }
1321 
1322  private:
1323   T value_;
1324 };
1325 
1326 // Specialization for lvalue reference types. See primary template
1327 // for documentation.
1328 template <typename T>
1329 class ReferenceOrValueWrapper<T&> {
1330  public:
1331   // Workaround for debatable pass-by-reference lint warning (c-library-team
1332   // policy precludes NOLINT in this context)
1333   typedef T& reference;
1334   explicit ReferenceOrValueWrapper(reference ref)
1335       : value_ptr_(&ref) {}
1336   T& Unwrap() { return *value_ptr_; }
1337   const T& Peek() const { return *value_ptr_; }
1338 
1339  private:
1340   T* value_ptr_;
1341 };
1342 
1343 // MSVC warns about using 'this' in base member initializer list, so
1344 // we need to temporarily disable the warning.  We have to do it for
1345 // the entire class to suppress the warning, even though it's about
1346 // the constructor only.
1347 
1348 #ifdef _MSC_VER
1349 # pragma warning(push)          // Saves the current warning state.
1350 # pragma warning(disable:4355)  // Temporarily disables warning 4355.
1351 #endif  // _MSV_VER
1352 
1353 // C++ treats the void type specially.  For example, you cannot define
1354 // a void-typed variable or pass a void value to a function.
1355 // ActionResultHolder<T> holds a value of type T, where T must be a
1356 // copyable type or void (T doesn't need to be default-constructable).
1357 // It hides the syntactic difference between void and other types, and
1358 // is used to unify the code for invoking both void-returning and
1359 // non-void-returning mock functions.
1360 
1361 // Untyped base class for ActionResultHolder<T>.
1362 class UntypedActionResultHolderBase {
1363  public:
1364   virtual ~UntypedActionResultHolderBase() {}
1365 
1366   // Prints the held value as an action's result to os.
1367   virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1368 };
1369 
1370 // This generic definition is used when T is not void.
1371 template <typename T>
1372 class ActionResultHolder : public UntypedActionResultHolderBase {
1373  public:
1374   // Returns the held value. Must not be called more than once.
1375   T Unwrap() {
1376     return result_.Unwrap();
1377   }
1378 
1379   // Prints the held value as an action's result to os.
1380   virtual void PrintAsActionResult(::std::ostream* os) const {
1381     *os << "\n          Returns: ";
1382     // T may be a reference type, so we don't use UniversalPrint().
1383     UniversalPrinter<T>::Print(result_.Peek(), os);
1384   }
1385 
1386   // Performs the given mock function's default action and returns the
1387   // result in a new-ed ActionResultHolder.
1388   template <typename F>
1389   static ActionResultHolder* PerformDefaultAction(
1390       const FunctionMockerBase<F>* func_mocker,
1391       const typename Function<F>::ArgumentTuple& args,
1392       const string& call_description) {
1393     return new ActionResultHolder(Wrapper(
1394         func_mocker->PerformDefaultAction(args, call_description)));
1395   }
1396 
1397   // Performs the given action and returns the result in a new-ed
1398   // ActionResultHolder.
1399   template <typename F>
1400   static ActionResultHolder*
1401   PerformAction(const Action<F>& action,
1402                 const typename Function<F>::ArgumentTuple& args) {
1403     return new ActionResultHolder(Wrapper(action.Perform(args)));
1404   }
1405 
1406  private:
1407   typedef ReferenceOrValueWrapper<T> Wrapper;
1408 
1409   explicit ActionResultHolder(Wrapper result)
1410       : result_(::testing::internal::move(result)) {
1411   }
1412 
1413   Wrapper result_;
1414 
1415   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1416 };
1417 
1418 // Specialization for T = void.
1419 template <>
1420 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1421  public:
1422   void Unwrap() { }
1423 
1424   virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1425 
1426   // Performs the given mock function's default action and returns ownership
1427   // of an empty ActionResultHolder*.
1428   template <typename F>
1429   static ActionResultHolder* PerformDefaultAction(
1430       const FunctionMockerBase<F>* func_mocker,
1431       const typename Function<F>::ArgumentTuple& args,
1432       const string& call_description) {
1433     func_mocker->PerformDefaultAction(args, call_description);
1434     return new ActionResultHolder;
1435   }
1436 
1437   // Performs the given action and returns ownership of an empty
1438   // ActionResultHolder*.
1439   template <typename F>
1440   static ActionResultHolder* PerformAction(
1441       const Action<F>& action,
1442       const typename Function<F>::ArgumentTuple& args) {
1443     action.Perform(args);
1444     return new ActionResultHolder;
1445   }
1446 
1447  private:
1448   ActionResultHolder() {}
1449   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1450 };
1451 
1452 // The base of the function mocker class for the given function type.
1453 // We put the methods in this class instead of its child to avoid code
1454 // bloat.
1455 template <typename F>
1456 class FunctionMockerBase : public UntypedFunctionMockerBase {
1457  public:
1458   typedef typename Function<F>::Result Result;
1459   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1460   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1461 
1462   FunctionMockerBase() : current_spec_(this) {}
1463 
1464   // The destructor verifies that all expectations on this mock
1465   // function have been satisfied.  If not, it will report Google Test
1466   // non-fatal failures for the violations.
1467   virtual ~FunctionMockerBase()
1468         GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1469     MutexLock l(&g_gmock_mutex);
1470     VerifyAndClearExpectationsLocked();
1471     Mock::UnregisterLocked(this);
1472     ClearDefaultActionsLocked();
1473   }
1474 
1475   // Returns the ON_CALL spec that matches this mock function with the
1476   // given arguments; returns NULL if no matching ON_CALL is found.
1477   // L = *
1478   const OnCallSpec<F>* FindOnCallSpec(
1479       const ArgumentTuple& args) const {
1480     for (UntypedOnCallSpecs::const_reverse_iterator it
1481              = untyped_on_call_specs_.rbegin();
1482          it != untyped_on_call_specs_.rend(); ++it) {
1483       const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1484       if (spec->Matches(args))
1485         return spec;
1486     }
1487 
1488     return NULL;
1489   }
1490 
1491   // Performs the default action of this mock function on the given
1492   // arguments and returns the result. Asserts (or throws if
1493   // exceptions are enabled) with a helpful call descrption if there
1494   // is no valid return value. This method doesn't depend on the
1495   // mutable state of this object, and thus can be called concurrently
1496   // without locking.
1497   // L = *
1498   Result PerformDefaultAction(const ArgumentTuple& args,
1499                               const string& call_description) const {
1500     const OnCallSpec<F>* const spec =
1501         this->FindOnCallSpec(args);
1502     if (spec != NULL) {
1503       return spec->GetAction().Perform(args);
1504     }
1505     const string message = call_description +
1506         "\n    The mock function has no default action "
1507         "set, and its return type has no default value set.";
1508 #if GTEST_HAS_EXCEPTIONS
1509     if (!DefaultValue<Result>::Exists()) {
1510       throw std::runtime_error(message);
1511     }
1512 #else
1513     Assert(DefaultValue<Result>::Exists(), "", -1, message);
1514 #endif
1515     return DefaultValue<Result>::Get();
1516   }
1517 
1518   // Performs the default action with the given arguments and returns
1519   // the action's result.  The call description string will be used in
1520   // the error message to describe the call in the case the default
1521   // action fails.  The caller is responsible for deleting the result.
1522   // L = *
1523   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1524       const void* untyped_args,  // must point to an ArgumentTuple
1525       const string& call_description) const {
1526     const ArgumentTuple& args =
1527         *static_cast<const ArgumentTuple*>(untyped_args);
1528     return ResultHolder::PerformDefaultAction(this, args, call_description);
1529   }
1530 
1531   // Performs the given action with the given arguments and returns
1532   // the action's result.  The caller is responsible for deleting the
1533   // result.
1534   // L = *
1535   virtual UntypedActionResultHolderBase* UntypedPerformAction(
1536       const void* untyped_action, const void* untyped_args) const {
1537     // Make a copy of the action before performing it, in case the
1538     // action deletes the mock object (and thus deletes itself).
1539     const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1540     const ArgumentTuple& args =
1541         *static_cast<const ArgumentTuple*>(untyped_args);
1542     return ResultHolder::PerformAction(action, args);
1543   }
1544 
1545   // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1546   // clears the ON_CALL()s set on this mock function.
1547   virtual void ClearDefaultActionsLocked()
1548       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1549     g_gmock_mutex.AssertHeld();
1550 
1551     // Deleting our default actions may trigger other mock objects to be
1552     // deleted, for example if an action contains a reference counted smart
1553     // pointer to that mock object, and that is the last reference. So if we
1554     // delete our actions within the context of the global mutex we may deadlock
1555     // when this method is called again. Instead, make a copy of the set of
1556     // actions to delete, clear our set within the mutex, and then delete the
1557     // actions outside of the mutex.
1558     UntypedOnCallSpecs specs_to_delete;
1559     untyped_on_call_specs_.swap(specs_to_delete);
1560 
1561     g_gmock_mutex.Unlock();
1562     for (UntypedOnCallSpecs::const_iterator it =
1563              specs_to_delete.begin();
1564          it != specs_to_delete.end(); ++it) {
1565       delete static_cast<const OnCallSpec<F>*>(*it);
1566     }
1567 
1568     // Lock the mutex again, since the caller expects it to be locked when we
1569     // return.
1570     g_gmock_mutex.Lock();
1571   }
1572 
1573  protected:
1574   template <typename Function>
1575   friend class MockSpec;
1576 
1577   typedef ActionResultHolder<Result> ResultHolder;
1578 
1579   // Returns the result of invoking this mock function with the given
1580   // arguments.  This function can be safely called from multiple
1581   // threads concurrently.
1582   Result InvokeWith(const ArgumentTuple& args)
1583         GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1584     scoped_ptr<ResultHolder> holder(
1585         DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
1586     return holder->Unwrap();
1587   }
1588 
1589   // Adds and returns a default action spec for this mock function.
1590   OnCallSpec<F>& AddNewOnCallSpec(
1591       const char* file, int line,
1592       const ArgumentMatcherTuple& m)
1593           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1594     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1595     OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1596     untyped_on_call_specs_.push_back(on_call_spec);
1597     return *on_call_spec;
1598   }
1599 
1600   // Adds and returns an expectation spec for this mock function.
1601   TypedExpectation<F>& AddNewExpectation(
1602       const char* file,
1603       int line,
1604       const string& source_text,
1605       const ArgumentMatcherTuple& m)
1606           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1607     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1608     TypedExpectation<F>* const expectation =
1609         new TypedExpectation<F>(this, file, line, source_text, m);
1610     const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1611     untyped_expectations_.push_back(untyped_expectation);
1612 
1613     // Adds this expectation into the implicit sequence if there is one.
1614     Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1615     if (implicit_sequence != NULL) {
1616       implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1617     }
1618 
1619     return *expectation;
1620   }
1621 
1622   // The current spec (either default action spec or expectation spec)
1623   // being described on this function mocker.
1624   MockSpec<F>& current_spec() { return current_spec_; }
1625 
1626  private:
1627   template <typename Func> friend class TypedExpectation;
1628 
1629   // Some utilities needed for implementing UntypedInvokeWith().
1630 
1631   // Describes what default action will be performed for the given
1632   // arguments.
1633   // L = *
1634   void DescribeDefaultActionTo(const ArgumentTuple& args,
1635                                ::std::ostream* os) const {
1636     const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1637 
1638     if (spec == NULL) {
1639       *os << (internal::type_equals<Result, void>::value ?
1640               "returning directly.\n" :
1641               "returning default value.\n");
1642     } else {
1643       *os << "taking default action specified at:\n"
1644           << FormatFileLocation(spec->file(), spec->line()) << "\n";
1645     }
1646   }
1647 
1648   // Writes a message that the call is uninteresting (i.e. neither
1649   // explicitly expected nor explicitly unexpected) to the given
1650   // ostream.
1651   virtual void UntypedDescribeUninterestingCall(
1652       const void* untyped_args,
1653       ::std::ostream* os) const
1654           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1655     const ArgumentTuple& args =
1656         *static_cast<const ArgumentTuple*>(untyped_args);
1657     *os << "Uninteresting mock function call - ";
1658     DescribeDefaultActionTo(args, os);
1659     *os << "    Function call: " << Name();
1660     UniversalPrint(args, os);
1661   }
1662 
1663   // Returns the expectation that matches the given function arguments
1664   // (or NULL is there's no match); when a match is found,
1665   // untyped_action is set to point to the action that should be
1666   // performed (or NULL if the action is "do default"), and
1667   // is_excessive is modified to indicate whether the call exceeds the
1668   // expected number.
1669   //
1670   // Critical section: We must find the matching expectation and the
1671   // corresponding action that needs to be taken in an ATOMIC
1672   // transaction.  Otherwise another thread may call this mock
1673   // method in the middle and mess up the state.
1674   //
1675   // However, performing the action has to be left out of the critical
1676   // section.  The reason is that we have no control on what the
1677   // action does (it can invoke an arbitrary user function or even a
1678   // mock function) and excessive locking could cause a dead lock.
1679   virtual const ExpectationBase* UntypedFindMatchingExpectation(
1680       const void* untyped_args,
1681       const void** untyped_action, bool* is_excessive,
1682       ::std::ostream* what, ::std::ostream* why)
1683           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1684     const ArgumentTuple& args =
1685         *static_cast<const ArgumentTuple*>(untyped_args);
1686     MutexLock l(&g_gmock_mutex);
1687     TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1688     if (exp == NULL) {  // A match wasn't found.
1689       this->FormatUnexpectedCallMessageLocked(args, what, why);
1690       return NULL;
1691     }
1692 
1693     // This line must be done before calling GetActionForArguments(),
1694     // which will increment the call count for *exp and thus affect
1695     // its saturation status.
1696     *is_excessive = exp->IsSaturated();
1697     const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1698     if (action != NULL && action->IsDoDefault())
1699       action = NULL;  // Normalize "do default" to NULL.
1700     *untyped_action = action;
1701     return exp;
1702   }
1703 
1704   // Prints the given function arguments to the ostream.
1705   virtual void UntypedPrintArgs(const void* untyped_args,
1706                                 ::std::ostream* os) const {
1707     const ArgumentTuple& args =
1708         *static_cast<const ArgumentTuple*>(untyped_args);
1709     UniversalPrint(args, os);
1710   }
1711 
1712   // Returns the expectation that matches the arguments, or NULL if no
1713   // expectation matches them.
1714   TypedExpectation<F>* FindMatchingExpectationLocked(
1715       const ArgumentTuple& args) const
1716           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1717     g_gmock_mutex.AssertHeld();
1718     for (typename UntypedExpectations::const_reverse_iterator it =
1719              untyped_expectations_.rbegin();
1720          it != untyped_expectations_.rend(); ++it) {
1721       TypedExpectation<F>* const exp =
1722           static_cast<TypedExpectation<F>*>(it->get());
1723       if (exp->ShouldHandleArguments(args)) {
1724         return exp;
1725       }
1726     }
1727     return NULL;
1728   }
1729 
1730   // Returns a message that the arguments don't match any expectation.
1731   void FormatUnexpectedCallMessageLocked(
1732       const ArgumentTuple& args,
1733       ::std::ostream* os,
1734       ::std::ostream* why) const
1735           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1736     g_gmock_mutex.AssertHeld();
1737     *os << "\nUnexpected mock function call - ";
1738     DescribeDefaultActionTo(args, os);
1739     PrintTriedExpectationsLocked(args, why);
1740   }
1741 
1742   // Prints a list of expectations that have been tried against the
1743   // current mock function call.
1744   void PrintTriedExpectationsLocked(
1745       const ArgumentTuple& args,
1746       ::std::ostream* why) const
1747           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1748     g_gmock_mutex.AssertHeld();
1749     const int count = static_cast<int>(untyped_expectations_.size());
1750     *why << "Google Mock tried the following " << count << " "
1751          << (count == 1 ? "expectation, but it didn't match" :
1752              "expectations, but none matched")
1753          << ":\n";
1754     for (int i = 0; i < count; i++) {
1755       TypedExpectation<F>* const expectation =
1756           static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1757       *why << "\n";
1758       expectation->DescribeLocationTo(why);
1759       if (count > 1) {
1760         *why << "tried expectation #" << i << ": ";
1761       }
1762       *why << expectation->source_text() << "...\n";
1763       expectation->ExplainMatchResultTo(args, why);
1764       expectation->DescribeCallCountTo(why);
1765     }
1766   }
1767 
1768   // The current spec (either default action spec or expectation spec)
1769   // being described on this function mocker.
1770   MockSpec<F> current_spec_;
1771 
1772   // There is no generally useful and implementable semantics of
1773   // copying a mock object, so copying a mock is usually a user error.
1774   // Thus we disallow copying function mockers.  If the user really
1775   // wants to copy a mock object, he should implement his own copy
1776   // operation, for example:
1777   //
1778   //   class MockFoo : public Foo {
1779   //    public:
1780   //     // Defines a copy constructor explicitly.
1781   //     MockFoo(const MockFoo& src) {}
1782   //     ...
1783   //   };
1784   GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1785 };  // class FunctionMockerBase
1786 
1787 #ifdef _MSC_VER
1788 # pragma warning(pop)  // Restores the warning state.
1789 #endif  // _MSV_VER
1790 
1791 // Implements methods of FunctionMockerBase.
1792 
1793 // Verifies that all expectations on this mock function have been
1794 // satisfied.  Reports one or more Google Test non-fatal failures and
1795 // returns false if not.
1796 
1797 // Reports an uninteresting call (whose description is in msg) in the
1798 // manner specified by 'reaction'.
1799 void ReportUninterestingCall(CallReaction reaction, const string& msg);
1800 
1801 }  // namespace internal
1802 
1803 // The style guide prohibits "using" statements in a namespace scope
1804 // inside a header file.  However, the MockSpec class template is
1805 // meant to be defined in the ::testing namespace.  The following line
1806 // is just a trick for working around a bug in MSVC 8.0, which cannot
1807 // handle it if we define MockSpec in ::testing.
1808 using internal::MockSpec;
1809 
1810 // Const(x) is a convenient function for obtaining a const reference
1811 // to x.  This is useful for setting expectations on an overloaded
1812 // const mock method, e.g.
1813 //
1814 //   class MockFoo : public FooInterface {
1815 //    public:
1816 //     MOCK_METHOD0(Bar, int());
1817 //     MOCK_CONST_METHOD0(Bar, int&());
1818 //   };
1819 //
1820 //   MockFoo foo;
1821 //   // Expects a call to non-const MockFoo::Bar().
1822 //   EXPECT_CALL(foo, Bar());
1823 //   // Expects a call to const MockFoo::Bar().
1824 //   EXPECT_CALL(Const(foo), Bar());
1825 template <typename T>
1826 inline const T& Const(const T& x) { return x; }
1827 
1828 // Constructs an Expectation object that references and co-owns exp.
1829 inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
1830     : expectation_base_(exp.GetHandle().expectation_base()) {}
1831 
1832 }  // namespace testing
1833 
1834 // A separate macro is required to avoid compile errors when the name
1835 // of the method used in call is a result of macro expansion.
1836 // See CompilesWithMethodNameExpandedFromMacro tests in
1837 // internal/gmock-spec-builders_test.cc for more details.
1838 #define GMOCK_ON_CALL_IMPL_(obj, call) \
1839     ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1840                                                     #obj, #call)
1841 #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
1842 
1843 #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
1844     ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
1845 #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
1846 
1847 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_