Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-06 08:19:54

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 Matcher<const string&>, Matcher<string>, and
0035 // utilities for defining matchers.
0036 
0037 #include "gmock/gmock-matchers.h"
0038 #include "gmock/gmock-generated-matchers.h"
0039 
0040 #include <string.h>
0041 #include <sstream>
0042 #include <string>
0043 
0044 namespace testing {
0045 
0046 // Constructs a matcher that matches a const string& whose value is
0047 // equal to s.
0048 Matcher<const internal::string&>::Matcher(const internal::string& s) {
0049   *this = Eq(s);
0050 }
0051 
0052 // Constructs a matcher that matches a const string& whose value is
0053 // equal to s.
0054 Matcher<const internal::string&>::Matcher(const char* s) {
0055   *this = Eq(internal::string(s));
0056 }
0057 
0058 // Constructs a matcher that matches a string whose value is equal to s.
0059 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
0060 
0061 // Constructs a matcher that matches a string whose value is equal to s.
0062 Matcher<internal::string>::Matcher(const char* s) {
0063   *this = Eq(internal::string(s));
0064 }
0065 
0066 #if GTEST_HAS_STRING_PIECE_
0067 // Constructs a matcher that matches a const StringPiece& whose value is
0068 // equal to s.
0069 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
0070   *this = Eq(s);
0071 }
0072 
0073 // Constructs a matcher that matches a const StringPiece& whose value is
0074 // equal to s.
0075 Matcher<const StringPiece&>::Matcher(const char* s) {
0076   *this = Eq(internal::string(s));
0077 }
0078 
0079 // Constructs a matcher that matches a const StringPiece& whose value is
0080 // equal to s.
0081 Matcher<const StringPiece&>::Matcher(StringPiece s) {
0082   *this = Eq(s.ToString());
0083 }
0084 
0085 // Constructs a matcher that matches a StringPiece whose value is equal to s.
0086 Matcher<StringPiece>::Matcher(const internal::string& s) {
0087   *this = Eq(s);
0088 }
0089 
0090 // Constructs a matcher that matches a StringPiece whose value is equal to s.
0091 Matcher<StringPiece>::Matcher(const char* s) {
0092   *this = Eq(internal::string(s));
0093 }
0094 
0095 // Constructs a matcher that matches a StringPiece whose value is equal to s.
0096 Matcher<StringPiece>::Matcher(StringPiece s) {
0097   *this = Eq(s.ToString());
0098 }
0099 #endif  // GTEST_HAS_STRING_PIECE_
0100 
0101 namespace internal {
0102 
0103 // Joins a vector of strings as if they are fields of a tuple; returns
0104 // the joined string.
0105 GTEST_API_ string JoinAsTuple(const Strings& fields) {
0106   switch (fields.size()) {
0107     case 0:
0108       return "";
0109     case 1:
0110       return fields[0];
0111     default:
0112       string result = "(" + fields[0];
0113       for (size_t i = 1; i < fields.size(); i++) {
0114         result += ", ";
0115         result += fields[i];
0116       }
0117       result += ")";
0118       return result;
0119   }
0120 }
0121 
0122 // Returns the description for a matcher defined using the MATCHER*()
0123 // macro where the user-supplied description string is "", if
0124 // 'negation' is false; otherwise returns the description of the
0125 // negation of the matcher.  'param_values' contains a list of strings
0126 // that are the print-out of the matcher's parameters.
0127 GTEST_API_ string FormatMatcherDescription(bool negation,
0128                                            const char* matcher_name,
0129                                            const Strings& param_values) {
0130   string result = ConvertIdentifierNameToWords(matcher_name);
0131   if (param_values.size() >= 1)
0132     result += " " + JoinAsTuple(param_values);
0133   return negation ? "not (" + result + ")" : result;
0134 }
0135 
0136 // FindMaxBipartiteMatching and its helper class.
0137 //
0138 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
0139 // bipartite matching. Flow is considered to be from left to right.
0140 // There is an implicit source node that is connected to all of the left
0141 // nodes, and an implicit sink node that is connected to all of the
0142 // right nodes. All edges have unit capacity.
0143 //
0144 // Neither the flow graph nor the residual flow graph are represented
0145 // explicitly. Instead, they are implied by the information in 'graph' and
0146 // a vector<int> called 'left_' whose elements are initialized to the
0147 // value kUnused. This represents the initial state of the algorithm,
0148 // where the flow graph is empty, and the residual flow graph has the
0149 // following edges:
0150 //   - An edge from source to each left_ node
0151 //   - An edge from each right_ node to sink
0152 //   - An edge from each left_ node to each right_ node, if the
0153 //     corresponding edge exists in 'graph'.
0154 //
0155 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
0156 // nodes l and r. This induces the following changes:
0157 //   - The edges (source, l), (l, r), and (r, sink) are added to the
0158 //     flow graph.
0159 //   - The same three edges are removed from the residual flow graph.
0160 //   - The reverse edges (l, source), (r, l), and (sink, r) are added
0161 //     to the residual flow graph, which is a directional graph
0162 //     representing unused flow capacity.
0163 //
0164 // When the method augments a flow (moving left_[l] from some r1 to some
0165 // other r2), this can be thought of as "undoing" the above steps with
0166 // respect to r1 and "redoing" them with respect to r2.
0167 //
0168 // It bears repeating that the flow graph and residual flow graph are
0169 // never represented explicitly, but can be derived by looking at the
0170 // information in 'graph' and in left_.
0171 //
0172 // As an optimization, there is a second vector<int> called right_ which
0173 // does not provide any new information. Instead, it enables more
0174 // efficient queries about edges entering or leaving the right-side nodes
0175 // of the flow or residual flow graphs. The following invariants are
0176 // maintained:
0177 //
0178 // left[l] == kUnused or right[left[l]] == l
0179 // right[r] == kUnused or left[right[r]] == r
0180 //
0181 // . [ source ]                                        .
0182 // .   |||                                             .
0183 // .   |||                                             .
0184 // .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
0185 // .   ||                   |                    |     .
0186 // .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
0187 // .   |                                        ||     .
0188 // .   \----> left[2]=2  ------> right[2]=2  --\||     .
0189 // .                                           |||     .
0190 // .         elements           matchers       vvv     .
0191 // .                                         [ sink ]  .
0192 //
0193 // See Also:
0194 //   [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
0195 //       "Introduction to Algorithms (Second ed.)", pp. 651-664.
0196 //   [2] "Ford-Fulkerson algorithm", Wikipedia,
0197 //       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
0198 class MaxBipartiteMatchState {
0199  public:
0200   explicit MaxBipartiteMatchState(const MatchMatrix& graph)
0201       : graph_(&graph),
0202         left_(graph_->LhsSize(), kUnused),
0203         right_(graph_->RhsSize(), kUnused) {
0204   }
0205 
0206   // Returns the edges of a maximal match, each in the form {left, right}.
0207   ElementMatcherPairs Compute() {
0208     // 'seen' is used for path finding { 0: unseen, 1: seen }.
0209     ::std::vector<char> seen;
0210     // Searches the residual flow graph for a path from each left node to
0211     // the sink in the residual flow graph, and if one is found, add flow
0212     // to the graph. It's okay to search through the left nodes once. The
0213     // edge from the implicit source node to each previously-visited left
0214     // node will have flow if that left node has any path to the sink
0215     // whatsoever. Subsequent augmentations can only add flow to the
0216     // network, and cannot take away that previous flow unit from the source.
0217     // Since the source-to-left edge can only carry one flow unit (or,
0218     // each element can be matched to only one matcher), there is no need
0219     // to visit the left nodes more than once looking for augmented paths.
0220     // The flow is known to be possible or impossible by looking at the
0221     // node once.
0222     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
0223       // Reset the path-marking vector and try to find a path from
0224       // source to sink starting at the left_[ilhs] node.
0225       GTEST_CHECK_(left_[ilhs] == kUnused)
0226           << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
0227       // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
0228       seen.assign(graph_->RhsSize(), 0);
0229       TryAugment(ilhs, &seen);
0230     }
0231     ElementMatcherPairs result;
0232     for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
0233       size_t irhs = left_[ilhs];
0234       if (irhs == kUnused) continue;
0235       result.push_back(ElementMatcherPair(ilhs, irhs));
0236     }
0237     return result;
0238   }
0239 
0240  private:
0241   static const size_t kUnused = static_cast<size_t>(-1);
0242 
0243   // Perform a depth-first search from left node ilhs to the sink.  If a
0244   // path is found, flow is added to the network by linking the left and
0245   // right vector elements corresponding each segment of the path.
0246   // Returns true if a path to sink was found, which means that a unit of
0247   // flow was added to the network. The 'seen' vector elements correspond
0248   // to right nodes and are marked to eliminate cycles from the search.
0249   //
0250   // Left nodes will only be explored at most once because they
0251   // are accessible from at most one right node in the residual flow
0252   // graph.
0253   //
0254   // Note that left_[ilhs] is the only element of left_ that TryAugment will
0255   // potentially transition from kUnused to another value. Any other
0256   // left_ element holding kUnused before TryAugment will be holding it
0257   // when TryAugment returns.
0258   //
0259   bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
0260     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
0261       if ((*seen)[irhs])
0262         continue;
0263       if (!graph_->HasEdge(ilhs, irhs))
0264         continue;
0265       // There's an available edge from ilhs to irhs.
0266       (*seen)[irhs] = 1;
0267       // Next a search is performed to determine whether
0268       // this edge is a dead end or leads to the sink.
0269       //
0270       // right_[irhs] == kUnused means that there is residual flow from
0271       // right node irhs to the sink, so we can use that to finish this
0272       // flow path and return success.
0273       //
0274       // Otherwise there is residual flow to some ilhs. We push flow
0275       // along that path and call ourselves recursively to see if this
0276       // ultimately leads to sink.
0277       if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
0278         // Add flow from left_[ilhs] to right_[irhs].
0279         left_[ilhs] = irhs;
0280         right_[irhs] = ilhs;
0281         return true;
0282       }
0283     }
0284     return false;
0285   }
0286 
0287   const MatchMatrix* graph_;  // not owned
0288   // Each element of the left_ vector represents a left hand side node
0289   // (i.e. an element) and each element of right_ is a right hand side
0290   // node (i.e. a matcher). The values in the left_ vector indicate
0291   // outflow from that node to a node on the the right_ side. The values
0292   // in the right_ indicate inflow, and specify which left_ node is
0293   // feeding that right_ node, if any. For example, left_[3] == 1 means
0294   // there's a flow from element #3 to matcher #1. Such a flow would also
0295   // be redundantly represented in the right_ vector as right_[1] == 3.
0296   // Elements of left_ and right_ are either kUnused or mutually
0297   // referent. Mutually referent means that left_[right_[i]] = i and
0298   // right_[left_[i]] = i.
0299   ::std::vector<size_t> left_;
0300   ::std::vector<size_t> right_;
0301 
0302   GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
0303 };
0304 
0305 const size_t MaxBipartiteMatchState::kUnused;
0306 
0307 GTEST_API_ ElementMatcherPairs
0308 FindMaxBipartiteMatching(const MatchMatrix& g) {
0309   return MaxBipartiteMatchState(g).Compute();
0310 }
0311 
0312 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
0313                                      ::std::ostream* stream) {
0314   typedef ElementMatcherPairs::const_iterator Iter;
0315   ::std::ostream& os = *stream;
0316   os << "{";
0317   const char *sep = "";
0318   for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
0319     os << sep << "\n  ("
0320        << "element #" << it->first << ", "
0321        << "matcher #" << it->second << ")";
0322     sep = ",";
0323   }
0324   os << "\n}";
0325 }
0326 
0327 // Tries to find a pairing, and explains the result.
0328 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
0329                             MatchResultListener* listener) {
0330   ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
0331 
0332   size_t max_flow = matches.size();
0333   bool result = (max_flow == matrix.RhsSize());
0334 
0335   if (!result) {
0336     if (listener->IsInterested()) {
0337       *listener << "where no permutation of the elements can "
0338                    "satisfy all matchers, and the closest match is "
0339                 << max_flow << " of " << matrix.RhsSize()
0340                 << " matchers with the pairings:\n";
0341       LogElementMatcherPairVec(matches, listener->stream());
0342     }
0343     return false;
0344   }
0345 
0346   if (matches.size() > 1) {
0347     if (listener->IsInterested()) {
0348       const char *sep = "where:\n";
0349       for (size_t mi = 0; mi < matches.size(); ++mi) {
0350         *listener << sep << " - element #" << matches[mi].first
0351                   << " is matched by matcher #" << matches[mi].second;
0352         sep = ",\n";
0353       }
0354     }
0355   }
0356   return true;
0357 }
0358 
0359 bool MatchMatrix::NextGraph() {
0360   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
0361     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
0362       char& b = matched_[SpaceIndex(ilhs, irhs)];
0363       if (!b) {
0364         b = 1;
0365         return true;
0366       }
0367       b = 0;
0368     }
0369   }
0370   return false;
0371 }
0372 
0373 void MatchMatrix::Randomize() {
0374   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
0375     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
0376       char& b = matched_[SpaceIndex(ilhs, irhs)];
0377       b = static_cast<char>(rand() & 1);  // NOLINT
0378     }
0379   }
0380 }
0381 
0382 string MatchMatrix::DebugString() const {
0383   ::std::stringstream ss;
0384   const char *sep = "";
0385   for (size_t i = 0; i < LhsSize(); ++i) {
0386     ss << sep;
0387     for (size_t j = 0; j < RhsSize(); ++j) {
0388       ss << HasEdge(i, j);
0389     }
0390     sep = ";";
0391   }
0392   return ss.str();
0393 }
0394 
0395 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
0396     ::std::ostream* os) const {
0397   if (matcher_describers_.empty()) {
0398     *os << "is empty";
0399     return;
0400   }
0401   if (matcher_describers_.size() == 1) {
0402     *os << "has " << Elements(1) << " and that element ";
0403     matcher_describers_[0]->DescribeTo(os);
0404     return;
0405   }
0406   *os << "has " << Elements(matcher_describers_.size())
0407       << " and there exists some permutation of elements such that:\n";
0408   const char* sep = "";
0409   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
0410     *os << sep << " - element #" << i << " ";
0411     matcher_describers_[i]->DescribeTo(os);
0412     sep = ", and\n";
0413   }
0414 }
0415 
0416 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
0417     ::std::ostream* os) const {
0418   if (matcher_describers_.empty()) {
0419     *os << "isn't empty";
0420     return;
0421   }
0422   if (matcher_describers_.size() == 1) {
0423     *os << "doesn't have " << Elements(1)
0424         << ", or has " << Elements(1) << " that ";
0425     matcher_describers_[0]->DescribeNegationTo(os);
0426     return;
0427   }
0428   *os << "doesn't have " << Elements(matcher_describers_.size())
0429       << ", or there exists no permutation of elements such that:\n";
0430   const char* sep = "";
0431   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
0432     *os << sep << " - element #" << i << " ";
0433     matcher_describers_[i]->DescribeTo(os);
0434     sep = ", and\n";
0435   }
0436 }
0437 
0438 // Checks that all matchers match at least one element, and that all
0439 // elements match at least one matcher. This enables faster matching
0440 // and better error reporting.
0441 // Returns false, writing an explanation to 'listener', if and only
0442 // if the success criteria are not met.
0443 bool UnorderedElementsAreMatcherImplBase::
0444 VerifyAllElementsAndMatchersAreMatched(
0445     const ::std::vector<string>& element_printouts,
0446     const MatchMatrix& matrix,
0447     MatchResultListener* listener) const {
0448   bool result = true;
0449   ::std::vector<char> element_matched(matrix.LhsSize(), 0);
0450   ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
0451 
0452   for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
0453     for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
0454       char matched = matrix.HasEdge(ilhs, irhs);
0455       element_matched[ilhs] |= matched;
0456       matcher_matched[irhs] |= matched;
0457     }
0458   }
0459 
0460   {
0461     const char* sep =
0462         "where the following matchers don't match any elements:\n";
0463     for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
0464       if (matcher_matched[mi])
0465         continue;
0466       result = false;
0467       if (listener->IsInterested()) {
0468         *listener << sep << "matcher #" << mi << ": ";
0469         matcher_describers_[mi]->DescribeTo(listener->stream());
0470         sep = ",\n";
0471       }
0472     }
0473   }
0474 
0475   {
0476     const char* sep =
0477         "where the following elements don't match any matchers:\n";
0478     const char* outer_sep = "";
0479     if (!result) {
0480       outer_sep = "\nand ";
0481     }
0482     for (size_t ei = 0; ei < element_matched.size(); ++ei) {
0483       if (element_matched[ei])
0484         continue;
0485       result = false;
0486       if (listener->IsInterested()) {
0487         *listener << outer_sep << sep << "element #" << ei << ": "
0488                   << element_printouts[ei];
0489         sep = ",\n";
0490         outer_sep = "";
0491       }
0492     }
0493   }
0494   return result;
0495 }
0496 
0497 }  // namespace internal
0498 }  // namespace testing