test: Bundle GTest/GMock 1.8.1 sources and provide a find script
[quassel.git] / 3rdparty / googletest-1.8.1 / googlemock / include / gmock / gmock-spec-builders.h
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file implements the ON_CALL() and EXPECT_CALL() macros.
34 //
35 // A user can use the ON_CALL() macro to specify the default action of
36 // a mock method.  The syntax is:
37 //
38 //   ON_CALL(mock_object, Method(argument-matchers))
39 //       .With(multi-argument-matcher)
40 //       .WillByDefault(action);
41 //
42 //  where the .With() clause is optional.
43 //
44 // A user can use the EXPECT_CALL() macro to specify an expectation on
45 // a mock method.  The syntax is:
46 //
47 //   EXPECT_CALL(mock_object, Method(argument-matchers))
48 //       .With(multi-argument-matchers)
49 //       .Times(cardinality)
50 //       .InSequence(sequences)
51 //       .After(expectations)
52 //       .WillOnce(action)
53 //       .WillRepeatedly(action)
54 //       .RetiresOnSaturation();
55 //
56 // where all clauses are optional, and .InSequence()/.After()/
57 // .WillOnce() can appear any number of times.
58
59 // GOOGLETEST_CM0002 DO NOT DELETE
60
61 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63
64 #include <map>
65 #include <set>
66 #include <sstream>
67 #include <string>
68 #include <vector>
69 #include "gmock/gmock-actions.h"
70 #include "gmock/gmock-cardinalities.h"
71 #include "gmock/gmock-matchers.h"
72 #include "gmock/internal/gmock-internal-utils.h"
73 #include "gmock/internal/gmock-port.h"
74 #include "gtest/gtest.h"
75
76 #if GTEST_HAS_EXCEPTIONS
77 # include <stdexcept>  // NOLINT
78 #endif
79
80 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
81 /* class A needs to have dll-interface to be used by clients of class B */)
82
83 namespace testing {
84
85 // An abstract handle of an expectation.
86 class Expectation;
87
88 // A set of expectation handles.
89 class ExpectationSet;
90
91 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
92 // and MUST NOT BE USED IN USER CODE!!!
93 namespace internal {
94
95 // Implements a mock function.
96 template <typename F> class FunctionMocker;
97
98 // Base class for expectations.
99 class ExpectationBase;
100
101 // Implements an expectation.
102 template <typename F> class TypedExpectation;
103
104 // Helper class for testing the Expectation class template.
105 class ExpectationTester;
106
107 // Base class for function mockers.
108 template <typename F> class FunctionMockerBase;
109
110 // Protects the mock object registry (in class Mock), all function
111 // mockers, and all expectations.
112 //
113 // The reason we don't use more fine-grained protection is: when a
114 // mock function Foo() is called, it needs to consult its expectations
115 // to see which one should be picked.  If another thread is allowed to
116 // call a mock function (either Foo() or a different one) at the same
117 // time, it could affect the "retired" attributes of Foo()'s
118 // expectations when InSequence() is used, and thus affect which
119 // expectation gets picked.  Therefore, we sequence all mock function
120 // calls to ensure the integrity of the mock objects' states.
121 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
122
123 // Untyped base class for ActionResultHolder<R>.
124 class UntypedActionResultHolderBase;
125
126 // Abstract base class of FunctionMockerBase.  This is the
127 // type-agnostic part of the function mocker interface.  Its pure
128 // virtual methods are implemented by FunctionMockerBase.
129 class GTEST_API_ UntypedFunctionMockerBase {
130  public:
131   UntypedFunctionMockerBase();
132   virtual ~UntypedFunctionMockerBase();
133
134   // Verifies that all expectations on this mock function have been
135   // satisfied.  Reports one or more Google Test non-fatal failures
136   // and returns false if not.
137   bool VerifyAndClearExpectationsLocked()
138       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
139
140   // Clears the ON_CALL()s set on this mock function.
141   virtual void ClearDefaultActionsLocked()
142       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
143
144   // In all of the following Untyped* functions, it's the caller's
145   // responsibility to guarantee the correctness of the arguments'
146   // types.
147
148   // Performs the default action with the given arguments and returns
149   // the action's result.  The call description string will be used in
150   // the error message to describe the call in the case the default
151   // action fails.
152   // L = *
153   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
154       void* untyped_args, const std::string& call_description) const = 0;
155
156   // Performs the given action with the given arguments and returns
157   // the action's result.
158   // L = *
159   virtual UntypedActionResultHolderBase* UntypedPerformAction(
160       const void* untyped_action, void* untyped_args) const = 0;
161
162   // Writes a message that the call is uninteresting (i.e. neither
163   // explicitly expected nor explicitly unexpected) to the given
164   // ostream.
165   virtual void UntypedDescribeUninterestingCall(
166       const void* untyped_args,
167       ::std::ostream* os) const
168           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
169
170   // Returns the expectation that matches the given function arguments
171   // (or NULL is there's no match); when a match is found,
172   // untyped_action is set to point to the action that should be
173   // performed (or NULL if the action is "do default"), and
174   // is_excessive is modified to indicate whether the call exceeds the
175   // expected number.
176   virtual const ExpectationBase* UntypedFindMatchingExpectation(
177       const void* untyped_args,
178       const void** untyped_action, bool* is_excessive,
179       ::std::ostream* what, ::std::ostream* why)
180           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
181
182   // Prints the given function arguments to the ostream.
183   virtual void UntypedPrintArgs(const void* untyped_args,
184                                 ::std::ostream* os) const = 0;
185
186   // Sets the mock object this mock method belongs to, and registers
187   // this information in the global mock registry.  Will be called
188   // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
189   // method.
190   // FIXME: rename to SetAndRegisterOwner().
191   void RegisterOwner(const void* mock_obj)
192       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
193
194   // Sets the mock object this mock method belongs to, and sets the
195   // name of the mock function.  Will be called upon each invocation
196   // of this mock function.
197   void SetOwnerAndName(const void* mock_obj, const char* name)
198       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
199
200   // Returns the mock object this mock method belongs to.  Must be
201   // called after RegisterOwner() or SetOwnerAndName() has been
202   // called.
203   const void* MockObject() const
204       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
205
206   // Returns the name of this mock method.  Must be called after
207   // SetOwnerAndName() has been called.
208   const char* Name() const
209       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
210
211   // Returns the result of invoking this mock function with the given
212   // arguments.  This function can be safely called from multiple
213   // threads concurrently.  The caller is responsible for deleting the
214   // result.
215   UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
216       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
217
218  protected:
219   typedef std::vector<const void*> UntypedOnCallSpecs;
220
221   typedef std::vector<internal::linked_ptr<ExpectationBase> >
222   UntypedExpectations;
223
224   // Returns an Expectation object that references and co-owns exp,
225   // which must be an expectation on this mock function.
226   Expectation GetHandleOf(ExpectationBase* exp);
227
228   // Address of the mock object this mock method belongs to.  Only
229   // valid after this mock method has been called or
230   // ON_CALL/EXPECT_CALL has been invoked on it.
231   const void* mock_obj_;  // Protected by g_gmock_mutex.
232
233   // Name of the function being mocked.  Only valid after this mock
234   // method has been called.
235   const char* name_;  // Protected by g_gmock_mutex.
236
237   // All default action specs for this function mocker.
238   UntypedOnCallSpecs untyped_on_call_specs_;
239
240   // All expectations for this function mocker.
241   //
242   // It's undefined behavior to interleave expectations (EXPECT_CALLs
243   // or ON_CALLs) and mock function calls.  Also, the order of
244   // expectations is important.  Therefore it's a logic race condition
245   // to read/write untyped_expectations_ concurrently.  In order for
246   // tools like tsan to catch concurrent read/write accesses to
247   // untyped_expectations, we deliberately leave accesses to it
248   // unprotected.
249   UntypedExpectations untyped_expectations_;
250 };  // class UntypedFunctionMockerBase
251
252 // Untyped base class for OnCallSpec<F>.
253 class UntypedOnCallSpecBase {
254  public:
255   // The arguments are the location of the ON_CALL() statement.
256   UntypedOnCallSpecBase(const char* a_file, int a_line)
257       : file_(a_file), line_(a_line), last_clause_(kNone) {}
258
259   // Where in the source file was the default action spec defined?
260   const char* file() const { return file_; }
261   int line() const { return line_; }
262
263  protected:
264   // Gives each clause in the ON_CALL() statement a name.
265   enum Clause {
266     // Do not change the order of the enum members!  The run-time
267     // syntax checking relies on it.
268     kNone,
269     kWith,
270     kWillByDefault
271   };
272
273   // Asserts that the ON_CALL() statement has a certain property.
274   void AssertSpecProperty(bool property,
275                           const std::string& failure_message) const {
276     Assert(property, file_, line_, failure_message);
277   }
278
279   // Expects that the ON_CALL() statement has a certain property.
280   void ExpectSpecProperty(bool property,
281                           const std::string& failure_message) const {
282     Expect(property, file_, line_, failure_message);
283   }
284
285   const char* file_;
286   int line_;
287
288   // The last clause in the ON_CALL() statement as seen so far.
289   // Initially kNone and changes as the statement is parsed.
290   Clause last_clause_;
291 };  // class UntypedOnCallSpecBase
292
293 // This template class implements an ON_CALL spec.
294 template <typename F>
295 class OnCallSpec : public UntypedOnCallSpecBase {
296  public:
297   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
298   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
299
300   // Constructs an OnCallSpec object from the information inside
301   // the parenthesis of an ON_CALL() statement.
302   OnCallSpec(const char* a_file, int a_line,
303              const ArgumentMatcherTuple& matchers)
304       : UntypedOnCallSpecBase(a_file, a_line),
305         matchers_(matchers),
306         // By default, extra_matcher_ should match anything.  However,
307         // we cannot initialize it with _ as that triggers a compiler
308         // bug in Symbian's C++ compiler (cannot decide between two
309         // overloaded constructors of Matcher<const ArgumentTuple&>).
310         extra_matcher_(A<const ArgumentTuple&>()) {
311   }
312
313   // Implements the .With() clause.
314   OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
315     // Makes sure this is called at most once.
316     ExpectSpecProperty(last_clause_ < kWith,
317                        ".With() cannot appear "
318                        "more than once in an ON_CALL().");
319     last_clause_ = kWith;
320
321     extra_matcher_ = m;
322     return *this;
323   }
324
325   // Implements the .WillByDefault() clause.
326   OnCallSpec& WillByDefault(const Action<F>& action) {
327     ExpectSpecProperty(last_clause_ < kWillByDefault,
328                        ".WillByDefault() must appear "
329                        "exactly once in an ON_CALL().");
330     last_clause_ = kWillByDefault;
331
332     ExpectSpecProperty(!action.IsDoDefault(),
333                        "DoDefault() cannot be used in ON_CALL().");
334     action_ = action;
335     return *this;
336   }
337
338   // Returns true iff the given arguments match the matchers.
339   bool Matches(const ArgumentTuple& args) const {
340     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
341   }
342
343   // Returns the action specified by the user.
344   const Action<F>& GetAction() const {
345     AssertSpecProperty(last_clause_ == kWillByDefault,
346                        ".WillByDefault() must appear exactly "
347                        "once in an ON_CALL().");
348     return action_;
349   }
350
351  private:
352   // The information in statement
353   //
354   //   ON_CALL(mock_object, Method(matchers))
355   //       .With(multi-argument-matcher)
356   //       .WillByDefault(action);
357   //
358   // is recorded in the data members like this:
359   //
360   //   source file that contains the statement => file_
361   //   line number of the statement            => line_
362   //   matchers                                => matchers_
363   //   multi-argument-matcher                  => extra_matcher_
364   //   action                                  => action_
365   ArgumentMatcherTuple matchers_;
366   Matcher<const ArgumentTuple&> extra_matcher_;
367   Action<F> action_;
368 };  // class OnCallSpec
369
370 // Possible reactions on uninteresting calls.
371 enum CallReaction {
372   kAllow,
373   kWarn,
374   kFail,
375 };
376
377 }  // namespace internal
378
379 // Utilities for manipulating mock objects.
380 class GTEST_API_ Mock {
381  public:
382   // The following public methods can be called concurrently.
383
384   // Tells Google Mock to ignore mock_obj when checking for leaked
385   // mock objects.
386   static void AllowLeak(const void* mock_obj)
387       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
388
389   // Verifies and clears all expectations on the given mock object.
390   // If the expectations aren't satisfied, generates one or more
391   // Google Test non-fatal failures and returns false.
392   static bool VerifyAndClearExpectations(void* mock_obj)
393       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
394
395   // Verifies all expectations on the given mock object and clears its
396   // default actions and expectations.  Returns true iff the
397   // verification was successful.
398   static bool VerifyAndClear(void* mock_obj)
399       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
400
401  private:
402   friend class internal::UntypedFunctionMockerBase;
403
404   // Needed for a function mocker to register itself (so that we know
405   // how to clear a mock object).
406   template <typename F>
407   friend class internal::FunctionMockerBase;
408
409   template <typename M>
410   friend class NiceMock;
411
412   template <typename M>
413   friend class NaggyMock;
414
415   template <typename M>
416   friend class StrictMock;
417
418   // Tells Google Mock to allow uninteresting calls on the given mock
419   // object.
420   static void AllowUninterestingCalls(const void* mock_obj)
421       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
422
423   // Tells Google Mock to warn the user about uninteresting calls on
424   // the given mock object.
425   static void WarnUninterestingCalls(const void* mock_obj)
426       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
427
428   // Tells Google Mock to fail uninteresting calls on the given mock
429   // object.
430   static void FailUninterestingCalls(const void* mock_obj)
431       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
432
433   // Tells Google Mock the given mock object is being destroyed and
434   // its entry in the call-reaction table should be removed.
435   static void UnregisterCallReaction(const void* mock_obj)
436       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
437
438   // Returns the reaction Google Mock will have on uninteresting calls
439   // made on the given mock object.
440   static internal::CallReaction GetReactionOnUninterestingCalls(
441       const void* mock_obj)
442           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
443
444   // Verifies that all expectations on the given mock object have been
445   // satisfied.  Reports one or more Google Test non-fatal failures
446   // and returns false if not.
447   static bool VerifyAndClearExpectationsLocked(void* mock_obj)
448       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
449
450   // Clears all ON_CALL()s set on the given mock object.
451   static void ClearDefaultActionsLocked(void* mock_obj)
452       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
453
454   // Registers a mock object and a mock method it owns.
455   static void Register(
456       const void* mock_obj,
457       internal::UntypedFunctionMockerBase* mocker)
458           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
459
460   // Tells Google Mock where in the source code mock_obj is used in an
461   // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
462   // information helps the user identify which object it is.
463   static void RegisterUseByOnCallOrExpectCall(
464       const void* mock_obj, const char* file, int line)
465           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
466
467   // Unregisters a mock method; removes the owning mock object from
468   // the registry when the last mock method associated with it has
469   // been unregistered.  This is called only in the destructor of
470   // FunctionMockerBase.
471   static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
472       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
473 };  // class Mock
474
475 // An abstract handle of an expectation.  Useful in the .After()
476 // clause of EXPECT_CALL() for setting the (partial) order of
477 // expectations.  The syntax:
478 //
479 //   Expectation e1 = EXPECT_CALL(...)...;
480 //   EXPECT_CALL(...).After(e1)...;
481 //
482 // sets two expectations where the latter can only be matched after
483 // the former has been satisfied.
484 //
485 // Notes:
486 //   - This class is copyable and has value semantics.
487 //   - Constness is shallow: a const Expectation object itself cannot
488 //     be modified, but the mutable methods of the ExpectationBase
489 //     object it references can be called via expectation_base().
490 //   - The constructors and destructor are defined out-of-line because
491 //     the Symbian WINSCW compiler wants to otherwise instantiate them
492 //     when it sees this class definition, at which point it doesn't have
493 //     ExpectationBase available yet, leading to incorrect destruction
494 //     in the linked_ptr (or compilation errors if using a checking
495 //     linked_ptr).
496 class GTEST_API_ Expectation {
497  public:
498   // Constructs a null object that doesn't reference any expectation.
499   Expectation();
500
501   ~Expectation();
502
503   // This single-argument ctor must not be explicit, in order to support the
504   //   Expectation e = EXPECT_CALL(...);
505   // syntax.
506   //
507   // A TypedExpectation object stores its pre-requisites as
508   // Expectation objects, and needs to call the non-const Retire()
509   // method on the ExpectationBase objects they reference.  Therefore
510   // Expectation must receive a *non-const* reference to the
511   // ExpectationBase object.
512   Expectation(internal::ExpectationBase& exp);  // NOLINT
513
514   // The compiler-generated copy ctor and operator= work exactly as
515   // intended, so we don't need to define our own.
516
517   // Returns true iff rhs references the same expectation as this object does.
518   bool operator==(const Expectation& rhs) const {
519     return expectation_base_ == rhs.expectation_base_;
520   }
521
522   bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
523
524  private:
525   friend class ExpectationSet;
526   friend class Sequence;
527   friend class ::testing::internal::ExpectationBase;
528   friend class ::testing::internal::UntypedFunctionMockerBase;
529
530   template <typename F>
531   friend class ::testing::internal::FunctionMockerBase;
532
533   template <typename F>
534   friend class ::testing::internal::TypedExpectation;
535
536   // This comparator is needed for putting Expectation objects into a set.
537   class Less {
538    public:
539     bool operator()(const Expectation& lhs, const Expectation& rhs) const {
540       return lhs.expectation_base_.get() < rhs.expectation_base_.get();
541     }
542   };
543
544   typedef ::std::set<Expectation, Less> Set;
545
546   Expectation(
547       const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
548
549   // Returns the expectation this object references.
550   const internal::linked_ptr<internal::ExpectationBase>&
551   expectation_base() const {
552     return expectation_base_;
553   }
554
555   // A linked_ptr that co-owns the expectation this handle references.
556   internal::linked_ptr<internal::ExpectationBase> expectation_base_;
557 };
558
559 // A set of expectation handles.  Useful in the .After() clause of
560 // EXPECT_CALL() for setting the (partial) order of expectations.  The
561 // syntax:
562 //
563 //   ExpectationSet es;
564 //   es += EXPECT_CALL(...)...;
565 //   es += EXPECT_CALL(...)...;
566 //   EXPECT_CALL(...).After(es)...;
567 //
568 // sets three expectations where the last one can only be matched
569 // after the first two have both been satisfied.
570 //
571 // This class is copyable and has value semantics.
572 class ExpectationSet {
573  public:
574   // A bidirectional iterator that can read a const element in the set.
575   typedef Expectation::Set::const_iterator const_iterator;
576
577   // An object stored in the set.  This is an alias of Expectation.
578   typedef Expectation::Set::value_type value_type;
579
580   // Constructs an empty set.
581   ExpectationSet() {}
582
583   // This single-argument ctor must not be explicit, in order to support the
584   //   ExpectationSet es = EXPECT_CALL(...);
585   // syntax.
586   ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
587     *this += Expectation(exp);
588   }
589
590   // This single-argument ctor implements implicit conversion from
591   // Expectation and thus must not be explicit.  This allows either an
592   // Expectation or an ExpectationSet to be used in .After().
593   ExpectationSet(const Expectation& e) {  // NOLINT
594     *this += e;
595   }
596
597   // The compiler-generator ctor and operator= works exactly as
598   // intended, so we don't need to define our own.
599
600   // Returns true iff rhs contains the same set of Expectation objects
601   // as this does.
602   bool operator==(const ExpectationSet& rhs) const {
603     return expectations_ == rhs.expectations_;
604   }
605
606   bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
607
608   // Implements the syntax
609   //   expectation_set += EXPECT_CALL(...);
610   ExpectationSet& operator+=(const Expectation& e) {
611     expectations_.insert(e);
612     return *this;
613   }
614
615   int size() const { return static_cast<int>(expectations_.size()); }
616
617   const_iterator begin() const { return expectations_.begin(); }
618   const_iterator end() const { return expectations_.end(); }
619
620  private:
621   Expectation::Set expectations_;
622 };
623
624
625 // Sequence objects are used by a user to specify the relative order
626 // in which the expectations should match.  They are copyable (we rely
627 // on the compiler-defined copy constructor and assignment operator).
628 class GTEST_API_ Sequence {
629  public:
630   // Constructs an empty sequence.
631   Sequence() : last_expectation_(new Expectation) {}
632
633   // Adds an expectation to this sequence.  The caller must ensure
634   // that no other thread is accessing this Sequence object.
635   void AddExpectation(const Expectation& expectation) const;
636
637  private:
638   // The last expectation in this sequence.  We use a linked_ptr here
639   // because Sequence objects are copyable and we want the copies to
640   // be aliases.  The linked_ptr allows the copies to co-own and share
641   // the same Expectation object.
642   internal::linked_ptr<Expectation> last_expectation_;
643 };  // class Sequence
644
645 // An object of this type causes all EXPECT_CALL() statements
646 // encountered in its scope to be put in an anonymous sequence.  The
647 // work is done in the constructor and destructor.  You should only
648 // create an InSequence object on the stack.
649 //
650 // The sole purpose for this class is to support easy definition of
651 // sequential expectations, e.g.
652 //
653 //   {
654 //     InSequence dummy;  // The name of the object doesn't matter.
655 //
656 //     // The following expectations must match in the order they appear.
657 //     EXPECT_CALL(a, Bar())...;
658 //     EXPECT_CALL(a, Baz())...;
659 //     ...
660 //     EXPECT_CALL(b, Xyz())...;
661 //   }
662 //
663 // You can create InSequence objects in multiple threads, as long as
664 // they are used to affect different mock objects.  The idea is that
665 // each thread can create and set up its own mocks as if it's the only
666 // thread.  However, for clarity of your tests we recommend you to set
667 // up mocks in the main thread unless you have a good reason not to do
668 // so.
669 class GTEST_API_ InSequence {
670  public:
671   InSequence();
672   ~InSequence();
673  private:
674   bool sequence_created_;
675
676   GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
677 } GTEST_ATTRIBUTE_UNUSED_;
678
679 namespace internal {
680
681 // Points to the implicit sequence introduced by a living InSequence
682 // object (if any) in the current thread or NULL.
683 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
684
685 // Base class for implementing expectations.
686 //
687 // There are two reasons for having a type-agnostic base class for
688 // Expectation:
689 //
690 //   1. We need to store collections of expectations of different
691 //   types (e.g. all pre-requisites of a particular expectation, all
692 //   expectations in a sequence).  Therefore these expectation objects
693 //   must share a common base class.
694 //
695 //   2. We can avoid binary code bloat by moving methods not depending
696 //   on the template argument of Expectation to the base class.
697 //
698 // This class is internal and mustn't be used by user code directly.
699 class GTEST_API_ ExpectationBase {
700  public:
701   // source_text is the EXPECT_CALL(...) source that created this Expectation.
702   ExpectationBase(const char* file, int line, const std::string& source_text);
703
704   virtual ~ExpectationBase();
705
706   // Where in the source file was the expectation spec defined?
707   const char* file() const { return file_; }
708   int line() const { return line_; }
709   const char* source_text() const { return source_text_.c_str(); }
710   // Returns the cardinality specified in the expectation spec.
711   const Cardinality& cardinality() const { return cardinality_; }
712
713   // Describes the source file location of this expectation.
714   void DescribeLocationTo(::std::ostream* os) const {
715     *os << FormatFileLocation(file(), line()) << " ";
716   }
717
718   // Describes how many times a function call matching this
719   // expectation has occurred.
720   void DescribeCallCountTo(::std::ostream* os) const
721       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
722
723   // If this mock method has an extra matcher (i.e. .With(matcher)),
724   // describes it to the ostream.
725   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
726
727  protected:
728   friend class ::testing::Expectation;
729   friend class UntypedFunctionMockerBase;
730
731   enum Clause {
732     // Don't change the order of the enum members!
733     kNone,
734     kWith,
735     kTimes,
736     kInSequence,
737     kAfter,
738     kWillOnce,
739     kWillRepeatedly,
740     kRetiresOnSaturation
741   };
742
743   typedef std::vector<const void*> UntypedActions;
744
745   // Returns an Expectation object that references and co-owns this
746   // expectation.
747   virtual Expectation GetHandle() = 0;
748
749   // Asserts that the EXPECT_CALL() statement has the given property.
750   void AssertSpecProperty(bool property,
751                           const std::string& failure_message) const {
752     Assert(property, file_, line_, failure_message);
753   }
754
755   // Expects that the EXPECT_CALL() statement has the given property.
756   void ExpectSpecProperty(bool property,
757                           const std::string& failure_message) const {
758     Expect(property, file_, line_, failure_message);
759   }
760
761   // Explicitly specifies the cardinality of this expectation.  Used
762   // by the subclasses to implement the .Times() clause.
763   void SpecifyCardinality(const Cardinality& cardinality);
764
765   // Returns true iff the user specified the cardinality explicitly
766   // using a .Times().
767   bool cardinality_specified() const { return cardinality_specified_; }
768
769   // Sets the cardinality of this expectation spec.
770   void set_cardinality(const Cardinality& a_cardinality) {
771     cardinality_ = a_cardinality;
772   }
773
774   // The following group of methods should only be called after the
775   // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
776   // the current thread.
777
778   // Retires all pre-requisites of this expectation.
779   void RetireAllPreRequisites()
780       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
781
782   // Returns true iff this expectation is retired.
783   bool is_retired() const
784       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
785     g_gmock_mutex.AssertHeld();
786     return retired_;
787   }
788
789   // Retires this expectation.
790   void Retire()
791       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
792     g_gmock_mutex.AssertHeld();
793     retired_ = true;
794   }
795
796   // Returns true iff this expectation is satisfied.
797   bool IsSatisfied() const
798       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
799     g_gmock_mutex.AssertHeld();
800     return cardinality().IsSatisfiedByCallCount(call_count_);
801   }
802
803   // Returns true iff this expectation is saturated.
804   bool IsSaturated() const
805       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
806     g_gmock_mutex.AssertHeld();
807     return cardinality().IsSaturatedByCallCount(call_count_);
808   }
809
810   // Returns true iff this expectation is over-saturated.
811   bool IsOverSaturated() const
812       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
813     g_gmock_mutex.AssertHeld();
814     return cardinality().IsOverSaturatedByCallCount(call_count_);
815   }
816
817   // Returns true iff all pre-requisites of this expectation are satisfied.
818   bool AllPrerequisitesAreSatisfied() const
819       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
820
821   // Adds unsatisfied pre-requisites of this expectation to 'result'.
822   void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
823       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
824
825   // Returns the number this expectation has been invoked.
826   int call_count() const
827       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
828     g_gmock_mutex.AssertHeld();
829     return call_count_;
830   }
831
832   // Increments the number this expectation has been invoked.
833   void IncrementCallCount()
834       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
835     g_gmock_mutex.AssertHeld();
836     call_count_++;
837   }
838
839   // Checks the action count (i.e. the number of WillOnce() and
840   // WillRepeatedly() clauses) against the cardinality if this hasn't
841   // been done before.  Prints a warning if there are too many or too
842   // few actions.
843   void CheckActionCountIfNotDone() const
844       GTEST_LOCK_EXCLUDED_(mutex_);
845
846   friend class ::testing::Sequence;
847   friend class ::testing::internal::ExpectationTester;
848
849   template <typename Function>
850   friend class TypedExpectation;
851
852   // Implements the .Times() clause.
853   void UntypedTimes(const Cardinality& a_cardinality);
854
855   // This group of fields are part of the spec and won't change after
856   // an EXPECT_CALL() statement finishes.
857   const char* file_;          // The file that contains the expectation.
858   int line_;                  // The line number of the expectation.
859   const std::string source_text_;  // The EXPECT_CALL(...) source text.
860   // True iff the cardinality is specified explicitly.
861   bool cardinality_specified_;
862   Cardinality cardinality_;            // The cardinality of the expectation.
863   // The immediate pre-requisites (i.e. expectations that must be
864   // satisfied before this expectation can be matched) of this
865   // expectation.  We use linked_ptr in the set because we want an
866   // Expectation object to be co-owned by its FunctionMocker and its
867   // successors.  This allows multiple mock objects to be deleted at
868   // different times.
869   ExpectationSet immediate_prerequisites_;
870
871   // This group of fields are the current state of the expectation,
872   // and can change as the mock function is called.
873   int call_count_;  // How many times this expectation has been invoked.
874   bool retired_;    // True iff this expectation has retired.
875   UntypedActions untyped_actions_;
876   bool extra_matcher_specified_;
877   bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
878   bool retires_on_saturation_;
879   Clause last_clause_;
880   mutable bool action_count_checked_;  // Under mutex_.
881   mutable Mutex mutex_;  // Protects action_count_checked_.
882
883   GTEST_DISALLOW_ASSIGN_(ExpectationBase);
884 };  // class ExpectationBase
885
886 // Impements an expectation for the given function type.
887 template <typename F>
888 class TypedExpectation : public ExpectationBase {
889  public:
890   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
891   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
892   typedef typename Function<F>::Result Result;
893
894   TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
895                    const std::string& a_source_text,
896                    const ArgumentMatcherTuple& m)
897       : ExpectationBase(a_file, a_line, a_source_text),
898         owner_(owner),
899         matchers_(m),
900         // By default, extra_matcher_ should match anything.  However,
901         // we cannot initialize it with _ as that triggers a compiler
902         // bug in Symbian's C++ compiler (cannot decide between two
903         // overloaded constructors of Matcher<const ArgumentTuple&>).
904         extra_matcher_(A<const ArgumentTuple&>()),
905         repeated_action_(DoDefault()) {}
906
907   virtual ~TypedExpectation() {
908     // Check the validity of the action count if it hasn't been done
909     // yet (for example, if the expectation was never used).
910     CheckActionCountIfNotDone();
911     for (UntypedActions::const_iterator it = untyped_actions_.begin();
912          it != untyped_actions_.end(); ++it) {
913       delete static_cast<const Action<F>*>(*it);
914     }
915   }
916
917   // Implements the .With() clause.
918   TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
919     if (last_clause_ == kWith) {
920       ExpectSpecProperty(false,
921                          ".With() cannot appear "
922                          "more than once in an EXPECT_CALL().");
923     } else {
924       ExpectSpecProperty(last_clause_ < kWith,
925                          ".With() must be the first "
926                          "clause in an EXPECT_CALL().");
927     }
928     last_clause_ = kWith;
929
930     extra_matcher_ = m;
931     extra_matcher_specified_ = true;
932     return *this;
933   }
934
935   // Implements the .Times() clause.
936   TypedExpectation& Times(const Cardinality& a_cardinality) {
937     ExpectationBase::UntypedTimes(a_cardinality);
938     return *this;
939   }
940
941   // Implements the .Times() clause.
942   TypedExpectation& Times(int n) {
943     return Times(Exactly(n));
944   }
945
946   // Implements the .InSequence() clause.
947   TypedExpectation& InSequence(const Sequence& s) {
948     ExpectSpecProperty(last_clause_ <= kInSequence,
949                        ".InSequence() cannot appear after .After(),"
950                        " .WillOnce(), .WillRepeatedly(), or "
951                        ".RetiresOnSaturation().");
952     last_clause_ = kInSequence;
953
954     s.AddExpectation(GetHandle());
955     return *this;
956   }
957   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
958     return InSequence(s1).InSequence(s2);
959   }
960   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
961                                const Sequence& s3) {
962     return InSequence(s1, s2).InSequence(s3);
963   }
964   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
965                                const Sequence& s3, const Sequence& s4) {
966     return InSequence(s1, s2, s3).InSequence(s4);
967   }
968   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
969                                const Sequence& s3, const Sequence& s4,
970                                const Sequence& s5) {
971     return InSequence(s1, s2, s3, s4).InSequence(s5);
972   }
973
974   // Implements that .After() clause.
975   TypedExpectation& After(const ExpectationSet& s) {
976     ExpectSpecProperty(last_clause_ <= kAfter,
977                        ".After() cannot appear after .WillOnce(),"
978                        " .WillRepeatedly(), or "
979                        ".RetiresOnSaturation().");
980     last_clause_ = kAfter;
981
982     for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
983       immediate_prerequisites_ += *it;
984     }
985     return *this;
986   }
987   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
988     return After(s1).After(s2);
989   }
990   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
991                           const ExpectationSet& s3) {
992     return After(s1, s2).After(s3);
993   }
994   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
995                           const ExpectationSet& s3, const ExpectationSet& s4) {
996     return After(s1, s2, s3).After(s4);
997   }
998   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
999                           const ExpectationSet& s3, const ExpectationSet& s4,
1000                           const ExpectationSet& s5) {
1001     return After(s1, s2, s3, s4).After(s5);
1002   }
1003
1004   // Implements the .WillOnce() clause.
1005   TypedExpectation& WillOnce(const Action<F>& action) {
1006     ExpectSpecProperty(last_clause_ <= kWillOnce,
1007                        ".WillOnce() cannot appear after "
1008                        ".WillRepeatedly() or .RetiresOnSaturation().");
1009     last_clause_ = kWillOnce;
1010
1011     untyped_actions_.push_back(new Action<F>(action));
1012     if (!cardinality_specified()) {
1013       set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1014     }
1015     return *this;
1016   }
1017
1018   // Implements the .WillRepeatedly() clause.
1019   TypedExpectation& WillRepeatedly(const Action<F>& action) {
1020     if (last_clause_ == kWillRepeatedly) {
1021       ExpectSpecProperty(false,
1022                          ".WillRepeatedly() cannot appear "
1023                          "more than once in an EXPECT_CALL().");
1024     } else {
1025       ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1026                          ".WillRepeatedly() cannot appear "
1027                          "after .RetiresOnSaturation().");
1028     }
1029     last_clause_ = kWillRepeatedly;
1030     repeated_action_specified_ = true;
1031
1032     repeated_action_ = action;
1033     if (!cardinality_specified()) {
1034       set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1035     }
1036
1037     // Now that no more action clauses can be specified, we check
1038     // whether their count makes sense.
1039     CheckActionCountIfNotDone();
1040     return *this;
1041   }
1042
1043   // Implements the .RetiresOnSaturation() clause.
1044   TypedExpectation& RetiresOnSaturation() {
1045     ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1046                        ".RetiresOnSaturation() cannot appear "
1047                        "more than once.");
1048     last_clause_ = kRetiresOnSaturation;
1049     retires_on_saturation_ = true;
1050
1051     // Now that no more action clauses can be specified, we check
1052     // whether their count makes sense.
1053     CheckActionCountIfNotDone();
1054     return *this;
1055   }
1056
1057   // Returns the matchers for the arguments as specified inside the
1058   // EXPECT_CALL() macro.
1059   const ArgumentMatcherTuple& matchers() const {
1060     return matchers_;
1061   }
1062
1063   // Returns the matcher specified by the .With() clause.
1064   const Matcher<const ArgumentTuple&>& extra_matcher() const {
1065     return extra_matcher_;
1066   }
1067
1068   // Returns the action specified by the .WillRepeatedly() clause.
1069   const Action<F>& repeated_action() const { return repeated_action_; }
1070
1071   // If this mock method has an extra matcher (i.e. .With(matcher)),
1072   // describes it to the ostream.
1073   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
1074     if (extra_matcher_specified_) {
1075       *os << "    Expected args: ";
1076       extra_matcher_.DescribeTo(os);
1077       *os << "\n";
1078     }
1079   }
1080
1081  private:
1082   template <typename Function>
1083   friend class FunctionMockerBase;
1084
1085   // Returns an Expectation object that references and co-owns this
1086   // expectation.
1087   virtual Expectation GetHandle() {
1088     return owner_->GetHandleOf(this);
1089   }
1090
1091   // The following methods will be called only after the EXPECT_CALL()
1092   // statement finishes and when the current thread holds
1093   // g_gmock_mutex.
1094
1095   // Returns true iff this expectation matches the given arguments.
1096   bool Matches(const ArgumentTuple& args) const
1097       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1098     g_gmock_mutex.AssertHeld();
1099     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1100   }
1101
1102   // Returns true iff this expectation should handle the given arguments.
1103   bool ShouldHandleArguments(const ArgumentTuple& args) const
1104       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1105     g_gmock_mutex.AssertHeld();
1106
1107     // In case the action count wasn't checked when the expectation
1108     // was defined (e.g. if this expectation has no WillRepeatedly()
1109     // or RetiresOnSaturation() clause), we check it when the
1110     // expectation is used for the first time.
1111     CheckActionCountIfNotDone();
1112     return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1113   }
1114
1115   // Describes the result of matching the arguments against this
1116   // expectation to the given ostream.
1117   void ExplainMatchResultTo(
1118       const ArgumentTuple& args,
1119       ::std::ostream* os) const
1120           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1121     g_gmock_mutex.AssertHeld();
1122
1123     if (is_retired()) {
1124       *os << "         Expected: the expectation is active\n"
1125           << "           Actual: it is retired\n";
1126     } else if (!Matches(args)) {
1127       if (!TupleMatches(matchers_, args)) {
1128         ExplainMatchFailureTupleTo(matchers_, args, os);
1129       }
1130       StringMatchResultListener listener;
1131       if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1132         *os << "    Expected args: ";
1133         extra_matcher_.DescribeTo(os);
1134         *os << "\n           Actual: don't match";
1135
1136         internal::PrintIfNotEmpty(listener.str(), os);
1137         *os << "\n";
1138       }
1139     } else if (!AllPrerequisitesAreSatisfied()) {
1140       *os << "         Expected: all pre-requisites are satisfied\n"
1141           << "           Actual: the following immediate pre-requisites "
1142           << "are not satisfied:\n";
1143       ExpectationSet unsatisfied_prereqs;
1144       FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1145       int i = 0;
1146       for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1147            it != unsatisfied_prereqs.end(); ++it) {
1148         it->expectation_base()->DescribeLocationTo(os);
1149         *os << "pre-requisite #" << i++ << "\n";
1150       }
1151       *os << "                   (end of pre-requisites)\n";
1152     } else {
1153       // This line is here just for completeness' sake.  It will never
1154       // be executed as currently the ExplainMatchResultTo() function
1155       // is called only when the mock function call does NOT match the
1156       // expectation.
1157       *os << "The call matches the expectation.\n";
1158     }
1159   }
1160
1161   // Returns the action that should be taken for the current invocation.
1162   const Action<F>& GetCurrentAction(
1163       const FunctionMockerBase<F>* mocker,
1164       const ArgumentTuple& args) const
1165           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1166     g_gmock_mutex.AssertHeld();
1167     const int count = call_count();
1168     Assert(count >= 1, __FILE__, __LINE__,
1169            "call_count() is <= 0 when GetCurrentAction() is "
1170            "called - this should never happen.");
1171
1172     const int action_count = static_cast<int>(untyped_actions_.size());
1173     if (action_count > 0 && !repeated_action_specified_ &&
1174         count > action_count) {
1175       // If there is at least one WillOnce() and no WillRepeatedly(),
1176       // we warn the user when the WillOnce() clauses ran out.
1177       ::std::stringstream ss;
1178       DescribeLocationTo(&ss);
1179       ss << "Actions ran out in " << source_text() << "...\n"
1180          << "Called " << count << " times, but only "
1181          << action_count << " WillOnce()"
1182          << (action_count == 1 ? " is" : "s are") << " specified - ";
1183       mocker->DescribeDefaultActionTo(args, &ss);
1184       Log(kWarning, ss.str(), 1);
1185     }
1186
1187     return count <= action_count ?
1188         *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1189         repeated_action();
1190   }
1191
1192   // Given the arguments of a mock function call, if the call will
1193   // over-saturate this expectation, returns the default action;
1194   // otherwise, returns the next action in this expectation.  Also
1195   // describes *what* happened to 'what', and explains *why* Google
1196   // Mock does it to 'why'.  This method is not const as it calls
1197   // IncrementCallCount().  A return value of NULL means the default
1198   // action.
1199   const Action<F>* GetActionForArguments(
1200       const FunctionMockerBase<F>* mocker,
1201       const ArgumentTuple& args,
1202       ::std::ostream* what,
1203       ::std::ostream* why)
1204           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1205     g_gmock_mutex.AssertHeld();
1206     if (IsSaturated()) {
1207       // We have an excessive call.
1208       IncrementCallCount();
1209       *what << "Mock function called more times than expected - ";
1210       mocker->DescribeDefaultActionTo(args, what);
1211       DescribeCallCountTo(why);
1212
1213       // FIXME: allow the user to control whether
1214       // unexpected calls should fail immediately or continue using a
1215       // flag --gmock_unexpected_calls_are_fatal.
1216       return NULL;
1217     }
1218
1219     IncrementCallCount();
1220     RetireAllPreRequisites();
1221
1222     if (retires_on_saturation_ && IsSaturated()) {
1223       Retire();
1224     }
1225
1226     // Must be done after IncrementCount()!
1227     *what << "Mock function call matches " << source_text() <<"...\n";
1228     return &(GetCurrentAction(mocker, args));
1229   }
1230
1231   // All the fields below won't change once the EXPECT_CALL()
1232   // statement finishes.
1233   FunctionMockerBase<F>* const owner_;
1234   ArgumentMatcherTuple matchers_;
1235   Matcher<const ArgumentTuple&> extra_matcher_;
1236   Action<F> repeated_action_;
1237
1238   GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1239 };  // class TypedExpectation
1240
1241 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1242 // specifying the default behavior of, or expectation on, a mock
1243 // function.
1244
1245 // Note: class MockSpec really belongs to the ::testing namespace.
1246 // However if we define it in ::testing, MSVC will complain when
1247 // classes in ::testing::internal declare it as a friend class
1248 // template.  To workaround this compiler bug, we define MockSpec in
1249 // ::testing::internal and import it into ::testing.
1250
1251 // Logs a message including file and line number information.
1252 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1253                                 const char* file, int line,
1254                                 const std::string& message);
1255
1256 template <typename F>
1257 class MockSpec {
1258  public:
1259   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1260   typedef typename internal::Function<F>::ArgumentMatcherTuple
1261       ArgumentMatcherTuple;
1262
1263   // Constructs a MockSpec object, given the function mocker object
1264   // that the spec is associated with.
1265   MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1266            const ArgumentMatcherTuple& matchers)
1267       : function_mocker_(function_mocker), matchers_(matchers) {}
1268
1269   // Adds a new default action spec to the function mocker and returns
1270   // the newly created spec.
1271   internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1272       const char* file, int line, const char* obj, const char* call) {
1273     LogWithLocation(internal::kInfo, file, line,
1274                     std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1275     return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1276   }
1277
1278   // Adds a new expectation spec to the function mocker and returns
1279   // the newly created spec.
1280   internal::TypedExpectation<F>& InternalExpectedAt(
1281       const char* file, int line, const char* obj, const char* call) {
1282     const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1283                                   call + ")");
1284     LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1285     return function_mocker_->AddNewExpectation(
1286         file, line, source_text, matchers_);
1287   }
1288
1289   // This operator overload is used to swallow the superfluous parameter list
1290   // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1291   // explanation.
1292   MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1293     return *this;
1294   }
1295
1296  private:
1297   template <typename Function>
1298   friend class internal::FunctionMocker;
1299
1300   // The function mocker that owns this spec.
1301   internal::FunctionMockerBase<F>* const function_mocker_;
1302   // The argument matchers specified in the spec.
1303   ArgumentMatcherTuple matchers_;
1304
1305   GTEST_DISALLOW_ASSIGN_(MockSpec);
1306 };  // class MockSpec
1307
1308 // Wrapper type for generically holding an ordinary value or lvalue reference.
1309 // If T is not a reference type, it must be copyable or movable.
1310 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1311 // T is a move-only value type (which means that it will always be copyable
1312 // if the current platform does not support move semantics).
1313 //
1314 // The primary template defines handling for values, but function header
1315 // comments describe the contract for the whole template (including
1316 // specializations).
1317 template <typename T>
1318 class ReferenceOrValueWrapper {
1319  public:
1320   // Constructs a wrapper from the given value/reference.
1321   explicit ReferenceOrValueWrapper(T value)
1322       : value_(::testing::internal::move(value)) {
1323   }
1324
1325   // Unwraps and returns the underlying value/reference, exactly as
1326   // originally passed. The behavior of calling this more than once on
1327   // the same object is unspecified.
1328   T Unwrap() { return ::testing::internal::move(value_); }
1329
1330   // Provides nondestructive access to the underlying value/reference.
1331   // Always returns a const reference (more precisely,
1332   // const RemoveReference<T>&). The behavior of calling this after
1333   // calling Unwrap on the same object is unspecified.
1334   const T& Peek() const {
1335     return value_;
1336   }
1337
1338  private:
1339   T value_;
1340 };
1341
1342 // Specialization for lvalue reference types. See primary template
1343 // for documentation.
1344 template <typename T>
1345 class ReferenceOrValueWrapper<T&> {
1346  public:
1347   // Workaround for debatable pass-by-reference lint warning (c-library-team
1348   // policy precludes NOLINT in this context)
1349   typedef T& reference;
1350   explicit ReferenceOrValueWrapper(reference ref)
1351       : value_ptr_(&ref) {}
1352   T& Unwrap() { return *value_ptr_; }
1353   const T& Peek() const { return *value_ptr_; }
1354
1355  private:
1356   T* value_ptr_;
1357 };
1358
1359 // MSVC warns about using 'this' in base member initializer list, so
1360 // we need to temporarily disable the warning.  We have to do it for
1361 // the entire class to suppress the warning, even though it's about
1362 // the constructor only.
1363 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
1364
1365 // C++ treats the void type specially.  For example, you cannot define
1366 // a void-typed variable or pass a void value to a function.
1367 // ActionResultHolder<T> holds a value of type T, where T must be a
1368 // copyable type or void (T doesn't need to be default-constructable).
1369 // It hides the syntactic difference between void and other types, and
1370 // is used to unify the code for invoking both void-returning and
1371 // non-void-returning mock functions.
1372
1373 // Untyped base class for ActionResultHolder<T>.
1374 class UntypedActionResultHolderBase {
1375  public:
1376   virtual ~UntypedActionResultHolderBase() {}
1377
1378   // Prints the held value as an action's result to os.
1379   virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1380 };
1381
1382 // This generic definition is used when T is not void.
1383 template <typename T>
1384 class ActionResultHolder : public UntypedActionResultHolderBase {
1385  public:
1386   // Returns the held value. Must not be called more than once.
1387   T Unwrap() {
1388     return result_.Unwrap();
1389   }
1390
1391   // Prints the held value as an action's result to os.
1392   virtual void PrintAsActionResult(::std::ostream* os) const {
1393     *os << "\n          Returns: ";
1394     // T may be a reference type, so we don't use UniversalPrint().
1395     UniversalPrinter<T>::Print(result_.Peek(), os);
1396   }
1397
1398   // Performs the given mock function's default action and returns the
1399   // result in a new-ed ActionResultHolder.
1400   template <typename F>
1401   static ActionResultHolder* PerformDefaultAction(
1402       const FunctionMockerBase<F>* func_mocker,
1403       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1404       const std::string& call_description) {
1405     return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1406         internal::move(args), call_description)));
1407   }
1408
1409   // Performs the given action and returns the result in a new-ed
1410   // ActionResultHolder.
1411   template <typename F>
1412   static ActionResultHolder* PerformAction(
1413       const Action<F>& action,
1414       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1415     return new ActionResultHolder(
1416         Wrapper(action.Perform(internal::move(args))));
1417   }
1418
1419  private:
1420   typedef ReferenceOrValueWrapper<T> Wrapper;
1421
1422   explicit ActionResultHolder(Wrapper result)
1423       : result_(::testing::internal::move(result)) {
1424   }
1425
1426   Wrapper result_;
1427
1428   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1429 };
1430
1431 // Specialization for T = void.
1432 template <>
1433 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1434  public:
1435   void Unwrap() { }
1436
1437   virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1438
1439   // Performs the given mock function's default action and returns ownership
1440   // of an empty ActionResultHolder*.
1441   template <typename F>
1442   static ActionResultHolder* PerformDefaultAction(
1443       const FunctionMockerBase<F>* func_mocker,
1444       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1445       const std::string& call_description) {
1446     func_mocker->PerformDefaultAction(internal::move(args), call_description);
1447     return new ActionResultHolder;
1448   }
1449
1450   // Performs the given action and returns ownership of an empty
1451   // ActionResultHolder*.
1452   template <typename F>
1453   static ActionResultHolder* PerformAction(
1454       const Action<F>& action,
1455       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1456     action.Perform(internal::move(args));
1457     return new ActionResultHolder;
1458   }
1459
1460  private:
1461   ActionResultHolder() {}
1462   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1463 };
1464
1465 // The base of the function mocker class for the given function type.
1466 // We put the methods in this class instead of its child to avoid code
1467 // bloat.
1468 template <typename F>
1469 class FunctionMockerBase : public UntypedFunctionMockerBase {
1470  public:
1471   typedef typename Function<F>::Result Result;
1472   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1473   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1474
1475   FunctionMockerBase() {}
1476
1477   // The destructor verifies that all expectations on this mock
1478   // function have been satisfied.  If not, it will report Google Test
1479   // non-fatal failures for the violations.
1480   virtual ~FunctionMockerBase()
1481         GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1482     MutexLock l(&g_gmock_mutex);
1483     VerifyAndClearExpectationsLocked();
1484     Mock::UnregisterLocked(this);
1485     ClearDefaultActionsLocked();
1486   }
1487
1488   // Returns the ON_CALL spec that matches this mock function with the
1489   // given arguments; returns NULL if no matching ON_CALL is found.
1490   // L = *
1491   const OnCallSpec<F>* FindOnCallSpec(
1492       const ArgumentTuple& args) const {
1493     for (UntypedOnCallSpecs::const_reverse_iterator it
1494              = untyped_on_call_specs_.rbegin();
1495          it != untyped_on_call_specs_.rend(); ++it) {
1496       const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1497       if (spec->Matches(args))
1498         return spec;
1499     }
1500
1501     return NULL;
1502   }
1503
1504   // Performs the default action of this mock function on the given
1505   // arguments and returns the result. Asserts (or throws if
1506   // exceptions are enabled) with a helpful call descrption if there
1507   // is no valid return value. This method doesn't depend on the
1508   // mutable state of this object, and thus can be called concurrently
1509   // without locking.
1510   // L = *
1511   Result PerformDefaultAction(
1512       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1513       const std::string& call_description) const {
1514     const OnCallSpec<F>* const spec =
1515         this->FindOnCallSpec(args);
1516     if (spec != NULL) {
1517       return spec->GetAction().Perform(internal::move(args));
1518     }
1519     const std::string message =
1520         call_description +
1521         "\n    The mock function has no default action "
1522         "set, and its return type has no default value set.";
1523 #if GTEST_HAS_EXCEPTIONS
1524     if (!DefaultValue<Result>::Exists()) {
1525       throw std::runtime_error(message);
1526     }
1527 #else
1528     Assert(DefaultValue<Result>::Exists(), "", -1, message);
1529 #endif
1530     return DefaultValue<Result>::Get();
1531   }
1532
1533   // Performs the default action with the given arguments and returns
1534   // the action's result.  The call description string will be used in
1535   // the error message to describe the call in the case the default
1536   // action fails.  The caller is responsible for deleting the result.
1537   // L = *
1538   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1539       void* untyped_args,  // must point to an ArgumentTuple
1540       const std::string& call_description) const {
1541     ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1542     return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1543                                               call_description);
1544   }
1545
1546   // Performs the given action with the given arguments and returns
1547   // the action's result.  The caller is responsible for deleting the
1548   // result.
1549   // L = *
1550   virtual UntypedActionResultHolderBase* UntypedPerformAction(
1551       const void* untyped_action, void* untyped_args) const {
1552     // Make a copy of the action before performing it, in case the
1553     // action deletes the mock object (and thus deletes itself).
1554     const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1555     ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1556     return ResultHolder::PerformAction(action, internal::move(*args));
1557   }
1558
1559   // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1560   // clears the ON_CALL()s set on this mock function.
1561   virtual void ClearDefaultActionsLocked()
1562       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1563     g_gmock_mutex.AssertHeld();
1564
1565     // Deleting our default actions may trigger other mock objects to be
1566     // deleted, for example if an action contains a reference counted smart
1567     // pointer to that mock object, and that is the last reference. So if we
1568     // delete our actions within the context of the global mutex we may deadlock
1569     // when this method is called again. Instead, make a copy of the set of
1570     // actions to delete, clear our set within the mutex, and then delete the
1571     // actions outside of the mutex.
1572     UntypedOnCallSpecs specs_to_delete;
1573     untyped_on_call_specs_.swap(specs_to_delete);
1574
1575     g_gmock_mutex.Unlock();
1576     for (UntypedOnCallSpecs::const_iterator it =
1577              specs_to_delete.begin();
1578          it != specs_to_delete.end(); ++it) {
1579       delete static_cast<const OnCallSpec<F>*>(*it);
1580     }
1581
1582     // Lock the mutex again, since the caller expects it to be locked when we
1583     // return.
1584     g_gmock_mutex.Lock();
1585   }
1586
1587  protected:
1588   template <typename Function>
1589   friend class MockSpec;
1590
1591   typedef ActionResultHolder<Result> ResultHolder;
1592
1593   // Returns the result of invoking this mock function with the given
1594   // arguments.  This function can be safely called from multiple
1595   // threads concurrently.
1596   Result InvokeWith(
1597       typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1598       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1599     // const_cast is required since in C++98 we still pass ArgumentTuple around
1600     // by const& instead of rvalue reference.
1601     void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
1602     scoped_ptr<ResultHolder> holder(
1603         DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
1604     return holder->Unwrap();
1605   }
1606
1607   // Adds and returns a default action spec for this mock function.
1608   OnCallSpec<F>& AddNewOnCallSpec(
1609       const char* file, int line,
1610       const ArgumentMatcherTuple& m)
1611           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1612     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1613     OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1614     untyped_on_call_specs_.push_back(on_call_spec);
1615     return *on_call_spec;
1616   }
1617
1618   // Adds and returns an expectation spec for this mock function.
1619   TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1620                                          const std::string& source_text,
1621                                          const ArgumentMatcherTuple& m)
1622       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1623     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1624     TypedExpectation<F>* const expectation =
1625         new TypedExpectation<F>(this, file, line, source_text, m);
1626     const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1627     // See the definition of untyped_expectations_ for why access to
1628     // it is unprotected here.
1629     untyped_expectations_.push_back(untyped_expectation);
1630
1631     // Adds this expectation into the implicit sequence if there is one.
1632     Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1633     if (implicit_sequence != NULL) {
1634       implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1635     }
1636
1637     return *expectation;
1638   }
1639
1640  private:
1641   template <typename Func> friend class TypedExpectation;
1642
1643   // Some utilities needed for implementing UntypedInvokeWith().
1644
1645   // Describes what default action will be performed for the given
1646   // arguments.
1647   // L = *
1648   void DescribeDefaultActionTo(const ArgumentTuple& args,
1649                                ::std::ostream* os) const {
1650     const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1651
1652     if (spec == NULL) {
1653       *os << (internal::type_equals<Result, void>::value ?
1654               "returning directly.\n" :
1655               "returning default value.\n");
1656     } else {
1657       *os << "taking default action specified at:\n"
1658           << FormatFileLocation(spec->file(), spec->line()) << "\n";
1659     }
1660   }
1661
1662   // Writes a message that the call is uninteresting (i.e. neither
1663   // explicitly expected nor explicitly unexpected) to the given
1664   // ostream.
1665   virtual void UntypedDescribeUninterestingCall(
1666       const void* untyped_args,
1667       ::std::ostream* os) const
1668           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1669     const ArgumentTuple& args =
1670         *static_cast<const ArgumentTuple*>(untyped_args);
1671     *os << "Uninteresting mock function call - ";
1672     DescribeDefaultActionTo(args, os);
1673     *os << "    Function call: " << Name();
1674     UniversalPrint(args, os);
1675   }
1676
1677   // Returns the expectation that matches the given function arguments
1678   // (or NULL is there's no match); when a match is found,
1679   // untyped_action is set to point to the action that should be
1680   // performed (or NULL if the action is "do default"), and
1681   // is_excessive is modified to indicate whether the call exceeds the
1682   // expected number.
1683   //
1684   // Critical section: We must find the matching expectation and the
1685   // corresponding action that needs to be taken in an ATOMIC
1686   // transaction.  Otherwise another thread may call this mock
1687   // method in the middle and mess up the state.
1688   //
1689   // However, performing the action has to be left out of the critical
1690   // section.  The reason is that we have no control on what the
1691   // action does (it can invoke an arbitrary user function or even a
1692   // mock function) and excessive locking could cause a dead lock.
1693   virtual const ExpectationBase* UntypedFindMatchingExpectation(
1694       const void* untyped_args,
1695       const void** untyped_action, bool* is_excessive,
1696       ::std::ostream* what, ::std::ostream* why)
1697           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1698     const ArgumentTuple& args =
1699         *static_cast<const ArgumentTuple*>(untyped_args);
1700     MutexLock l(&g_gmock_mutex);
1701     TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1702     if (exp == NULL) {  // A match wasn't found.
1703       this->FormatUnexpectedCallMessageLocked(args, what, why);
1704       return NULL;
1705     }
1706
1707     // This line must be done before calling GetActionForArguments(),
1708     // which will increment the call count for *exp and thus affect
1709     // its saturation status.
1710     *is_excessive = exp->IsSaturated();
1711     const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1712     if (action != NULL && action->IsDoDefault())
1713       action = NULL;  // Normalize "do default" to NULL.
1714     *untyped_action = action;
1715     return exp;
1716   }
1717
1718   // Prints the given function arguments to the ostream.
1719   virtual void UntypedPrintArgs(const void* untyped_args,
1720                                 ::std::ostream* os) const {
1721     const ArgumentTuple& args =
1722         *static_cast<const ArgumentTuple*>(untyped_args);
1723     UniversalPrint(args, os);
1724   }
1725
1726   // Returns the expectation that matches the arguments, or NULL if no
1727   // expectation matches them.
1728   TypedExpectation<F>* FindMatchingExpectationLocked(
1729       const ArgumentTuple& args) const
1730           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1731     g_gmock_mutex.AssertHeld();
1732     // See the definition of untyped_expectations_ for why access to
1733     // it is unprotected here.
1734     for (typename UntypedExpectations::const_reverse_iterator it =
1735              untyped_expectations_.rbegin();
1736          it != untyped_expectations_.rend(); ++it) {
1737       TypedExpectation<F>* const exp =
1738           static_cast<TypedExpectation<F>*>(it->get());
1739       if (exp->ShouldHandleArguments(args)) {
1740         return exp;
1741       }
1742     }
1743     return NULL;
1744   }
1745
1746   // Returns a message that the arguments don't match any expectation.
1747   void FormatUnexpectedCallMessageLocked(
1748       const ArgumentTuple& args,
1749       ::std::ostream* os,
1750       ::std::ostream* why) const
1751           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1752     g_gmock_mutex.AssertHeld();
1753     *os << "\nUnexpected mock function call - ";
1754     DescribeDefaultActionTo(args, os);
1755     PrintTriedExpectationsLocked(args, why);
1756   }
1757
1758   // Prints a list of expectations that have been tried against the
1759   // current mock function call.
1760   void PrintTriedExpectationsLocked(
1761       const ArgumentTuple& args,
1762       ::std::ostream* why) const
1763           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1764     g_gmock_mutex.AssertHeld();
1765     const int count = static_cast<int>(untyped_expectations_.size());
1766     *why << "Google Mock tried the following " << count << " "
1767          << (count == 1 ? "expectation, but it didn't match" :
1768              "expectations, but none matched")
1769          << ":\n";
1770     for (int i = 0; i < count; i++) {
1771       TypedExpectation<F>* const expectation =
1772           static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1773       *why << "\n";
1774       expectation->DescribeLocationTo(why);
1775       if (count > 1) {
1776         *why << "tried expectation #" << i << ": ";
1777       }
1778       *why << expectation->source_text() << "...\n";
1779       expectation->ExplainMatchResultTo(args, why);
1780       expectation->DescribeCallCountTo(why);
1781     }
1782   }
1783
1784   // There is no generally useful and implementable semantics of
1785   // copying a mock object, so copying a mock is usually a user error.
1786   // Thus we disallow copying function mockers.  If the user really
1787   // wants to copy a mock object, they should implement their own copy
1788   // operation, for example:
1789   //
1790   //   class MockFoo : public Foo {
1791   //    public:
1792   //     // Defines a copy constructor explicitly.
1793   //     MockFoo(const MockFoo& src) {}
1794   //     ...
1795   //   };
1796   GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1797 };  // class FunctionMockerBase
1798
1799 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4355
1800
1801 // Implements methods of FunctionMockerBase.
1802
1803 // Verifies that all expectations on this mock function have been
1804 // satisfied.  Reports one or more Google Test non-fatal failures and
1805 // returns false if not.
1806
1807 // Reports an uninteresting call (whose description is in msg) in the
1808 // manner specified by 'reaction'.
1809 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
1810
1811 }  // namespace internal
1812
1813 // The style guide prohibits "using" statements in a namespace scope
1814 // inside a header file.  However, the MockSpec class template is
1815 // meant to be defined in the ::testing namespace.  The following line
1816 // is just a trick for working around a bug in MSVC 8.0, which cannot
1817 // handle it if we define MockSpec in ::testing.
1818 using internal::MockSpec;
1819
1820 // Const(x) is a convenient function for obtaining a const reference
1821 // to x.  This is useful for setting expectations on an overloaded
1822 // const mock method, e.g.
1823 //
1824 //   class MockFoo : public FooInterface {
1825 //    public:
1826 //     MOCK_METHOD0(Bar, int());
1827 //     MOCK_CONST_METHOD0(Bar, int&());
1828 //   };
1829 //
1830 //   MockFoo foo;
1831 //   // Expects a call to non-const MockFoo::Bar().
1832 //   EXPECT_CALL(foo, Bar());
1833 //   // Expects a call to const MockFoo::Bar().
1834 //   EXPECT_CALL(Const(foo), Bar());
1835 template <typename T>
1836 inline const T& Const(const T& x) { return x; }
1837
1838 // Constructs an Expectation object that references and co-owns exp.
1839 inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
1840     : expectation_base_(exp.GetHandle().expectation_base()) {}
1841
1842 }  // namespace testing
1843
1844 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
1845
1846 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1847 // required to avoid compile errors when the name of the method used in call is
1848 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1849 // tests in internal/gmock-spec-builders_test.cc for more details.
1850 //
1851 // This macro supports statements both with and without parameter matchers. If
1852 // the parameter list is omitted, gMock will accept any parameters, which allows
1853 // tests to be written that don't need to encode the number of method
1854 // parameter. This technique may only be used for non-overloaded methods.
1855 //
1856 //   // These are the same:
1857 //   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1858 //   ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1859 //
1860 //   // As are these:
1861 //   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1862 //   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1863 //
1864 //   // Can also specify args if you want, of course:
1865 //   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1866 //
1867 //   // Overloads work as long as you specify parameters:
1868 //   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1869 //   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1870 //
1871 //   // Oops! Which overload did you want?
1872 //   ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1873 //     => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1874 //
1875 // How this works: The mock class uses two overloads of the gmock_Method
1876 // expectation setter method plus an operator() overload on the MockSpec object.
1877 // In the matcher list form, the macro expands to:
1878 //
1879 //   // This statement:
1880 //   ON_CALL(mock, TwoArgsMethod(_, 45))...
1881 //
1882 //   // ...expands to:
1883 //   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1884 //   |-------------v---------------||------------v-------------|
1885 //       invokes first overload        swallowed by operator()
1886 //
1887 //   // ...which is essentially:
1888 //   mock.gmock_TwoArgsMethod(_, 45)...
1889 //
1890 // Whereas the form without a matcher list:
1891 //
1892 //   // This statement:
1893 //   ON_CALL(mock, TwoArgsMethod)...
1894 //
1895 //   // ...expands to:
1896 //   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1897 //   |-----------------------v--------------------------|
1898 //                 invokes second overload
1899 //
1900 //   // ...which is essentially:
1901 //   mock.gmock_TwoArgsMethod(_, _)...
1902 //
1903 // The WithoutMatchers() argument is used to disambiguate overloads and to
1904 // block the caller from accidentally invoking the second overload directly. The
1905 // second argument is an internal type derived from the method signature. The
1906 // failure to disambiguate two overloads of this method in the ON_CALL statement
1907 // is how we block callers from setting expectations on overloaded methods.
1908 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                          \
1909   ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
1910       .Setter(__FILE__, __LINE__, #mock_expr, #call)
1911
1912 #define ON_CALL(obj, call) \
1913   GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1914
1915 #define EXPECT_CALL(obj, call) \
1916   GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1917
1918 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_