Debian Codegraph @

LspCpp/third_party/uri/deps/googlemock/src/gmock-matchers.cc

raw
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 Matcher<const string&>, Matcher<string>, and
34 // utilities for defining matchers.
35
36 #include "gmock/gmock-matchers.h"
37
38 #include <string.h>
39
40 #include <iostream>
41 #include <sstream>
42 #include <string>
43 #include <vector>
44
45 namespace testing {
46 namespace internal {
47
48 // Returns the description for a matcher defined using the MATCHER*()
49 // macro where the user-supplied description string is "", if
50 // 'negation' is false; otherwise returns the description of the
51 // negation of the matcher. 'param_values' contains a list of strings
52 // that are the print-out of the matcher's parameters.
53 GTEST_API_ std::string FormatMatcherDescription(
54 bool negation, const char* matcher_name,
55 const std::vector<const char*>& param_names, const Strings& param_values) {
56 std::string result = ConvertIdentifierNameToWords(matcher_name);
57 if (param_values.size() >= 1) {
58 result += " " + JoinAsKeyValueTuple(param_names, param_values);
59 }
60 return negation ? "not (" + result + ")" : result;
61 }
62
63 // FindMaxBipartiteMatching and its helper class.
64 //
65 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
66 // bipartite matching. Flow is considered to be from left to right.
67 // There is an implicit source node that is connected to all of the left
68 // nodes, and an implicit sink node that is connected to all of the
69 // right nodes. All edges have unit capacity.
70 //
71 // Neither the flow graph nor the residual flow graph are represented
72 // explicitly. Instead, they are implied by the information in 'graph' and
73 // a vector<int> called 'left_' whose elements are initialized to the
74 // value kUnused. This represents the initial state of the algorithm,
75 // where the flow graph is empty, and the residual flow graph has the
76 // following edges:
77 // - An edge from source to each left_ node
78 // - An edge from each right_ node to sink
79 // - An edge from each left_ node to each right_ node, if the
80 // corresponding edge exists in 'graph'.
81 //
82 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
83 // nodes l and r. This induces the following changes:
84 // - The edges (source, l), (l, r), and (r, sink) are added to the
85 // flow graph.
86 // - The same three edges are removed from the residual flow graph.
87 // - The reverse edges (l, source), (r, l), and (sink, r) are added
88 // to the residual flow graph, which is a directional graph
89 // representing unused flow capacity.
90 //
91 // When the method augments a flow (moving left_[l] from some r1 to some
92 // other r2), this can be thought of as "undoing" the above steps with
93 // respect to r1 and "redoing" them with respect to r2.
94 //
95 // It bears repeating that the flow graph and residual flow graph are
96 // never represented explicitly, but can be derived by looking at the
97 // information in 'graph' and in left_.
98 //
99 // As an optimization, there is a second vector<int> called right_ which
100 // does not provide any new information. Instead, it enables more
101 // efficient queries about edges entering or leaving the right-side nodes
102 // of the flow or residual flow graphs. The following invariants are
103 // maintained:
104 //
105 // left[l] == kUnused or right[left[l]] == l
106 // right[r] == kUnused or left[right[r]] == r
107 //
108 // . [ source ] .
109 // . ||| .
110 // . ||| .
111 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
112 // . || | | .
113 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
114 // . | || .
115 // . \----> left[2]=2 ------> right[2]=2 --\|| .
116 // . ||| .
117 // . elements matchers vvv .
118 // . [ sink ] .
119 //
120 // See Also:
121 // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
122 // "Introduction to Algorithms (Second ed.)", pp. 651-664.
123 // [2] "Ford-Fulkerson algorithm", Wikipedia,
124 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
125 class MaxBipartiteMatchState {
126 public:
127 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
128 : graph_(&graph),
129 left_(graph_->LhsSize(), kUnused),
130 right_(graph_->RhsSize(), kUnused) {}
131
132 // Returns the edges of a maximal match, each in the form {left, right}.
133 ElementMatcherPairs Compute() {
134 // 'seen' is used for path finding { 0: unseen, 1: seen }.
135 ::std::vector<char> seen;
136 // Searches the residual flow graph for a path from each left node to
137 // the sink in the residual flow graph, and if one is found, add flow
138 // to the graph. It's okay to search through the left nodes once. The
139 // edge from the implicit source node to each previously-visited left
140 // node will have flow if that left node has any path to the sink
141 // whatsoever. Subsequent augmentations can only add flow to the
142 // network, and cannot take away that previous flow unit from the source.
143 // Since the source-to-left edge can only carry one flow unit (or,
144 // each element can be matched to only one matcher), there is no need
145 // to visit the left nodes more than once looking for augmented paths.
146 // The flow is known to be possible or impossible by looking at the
147 // node once.
148 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
149 // Reset the path-marking vector and try to find a path from
150 // source to sink starting at the left_[ilhs] node.
151 GTEST_CHECK_(left_[ilhs] == kUnused)
152 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
153 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
154 seen.assign(graph_->RhsSize(), 0);
155 TryAugment(ilhs, &seen);
156 }
157 ElementMatcherPairs result;
158 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
159 size_t irhs = left_[ilhs];
160 if (irhs == kUnused) continue;
161 result.push_back(ElementMatcherPair(ilhs, irhs));
162 }
163 return result;
164 }
165
166 private:
167 static const size_t kUnused = static_cast<size_t>(-1);
168
169 // Perform a depth-first search from left node ilhs to the sink. If a
170 // path is found, flow is added to the network by linking the left and
171 // right vector elements corresponding each segment of the path.
172 // Returns true if a path to sink was found, which means that a unit of
173 // flow was added to the network. The 'seen' vector elements correspond
174 // to right nodes and are marked to eliminate cycles from the search.
175 //
176 // Left nodes will only be explored at most once because they
177 // are accessible from at most one right node in the residual flow
178 // graph.
179 //
180 // Note that left_[ilhs] is the only element of left_ that TryAugment will
181 // potentially transition from kUnused to another value. Any other
182 // left_ element holding kUnused before TryAugment will be holding it
183 // when TryAugment returns.
184 //
185 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
186 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
187 if ((*seen)[irhs]) continue;
188 if (!graph_->HasEdge(ilhs, irhs)) continue;
189 // There's an available edge from ilhs to irhs.
190 (*seen)[irhs] = 1;
191 // Next a search is performed to determine whether
192 // this edge is a dead end or leads to the sink.
193 //
194 // right_[irhs] == kUnused means that there is residual flow from
195 // right node irhs to the sink, so we can use that to finish this
196 // flow path and return success.
197 //
198 // Otherwise there is residual flow to some ilhs. We push flow
199 // along that path and call ourselves recursively to see if this
200 // ultimately leads to sink.
201 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
202 // Add flow from left_[ilhs] to right_[irhs].
203 left_[ilhs] = irhs;
204 right_[irhs] = ilhs;
205 return true;
206 }
207 }
208 return false;
209 }
210
211 const MatchMatrix* graph_; // not owned
212 // Each element of the left_ vector represents a left hand side node
213 // (i.e. an element) and each element of right_ is a right hand side
214 // node (i.e. a matcher). The values in the left_ vector indicate
215 // outflow from that node to a node on the right_ side. The values
216 // in the right_ indicate inflow, and specify which left_ node is
217 // feeding that right_ node, if any. For example, left_[3] == 1 means
218 // there's a flow from element #3 to matcher #1. Such a flow would also
219 // be redundantly represented in the right_ vector as right_[1] == 3.
220 // Elements of left_ and right_ are either kUnused or mutually
221 // referent. Mutually referent means that left_[right_[i]] = i and
222 // right_[left_[i]] = i.
223 ::std::vector<size_t> left_;
224 ::std::vector<size_t> right_;
225 };
226
227 const size_t MaxBipartiteMatchState::kUnused;
228
229 GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
230 return MaxBipartiteMatchState(g).Compute();
231 }
232
233 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
234 ::std::ostream* stream) {
235 typedef ElementMatcherPairs::const_iterator Iter;
236 ::std::ostream& os = *stream;
237 os << "{";
238 const char* sep = "";
239 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
240 os << sep << "\n ("
241 << "element #" << it->first << ", "
242 << "matcher #" << it->second << ")";
243 sep = ",";
244 }
245 os << "\n}";
246 }
247
248 bool MatchMatrix::NextGraph() {
249 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
250 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
251 char& b = matched_[SpaceIndex(ilhs, irhs)];
252 if (!b) {
253 b = 1;
254 return true;
255 }
256 b = 0;
257 }
258 }
259 return false;
260 }
261
262 void MatchMatrix::Randomize() {
263 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
264 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
265 char& b = matched_[SpaceIndex(ilhs, irhs)];
266 b = static_cast<char>(rand() & 1); // NOLINT
267 }
268 }
269 }
270
271 std::string MatchMatrix::DebugString() const {
272 ::std::stringstream ss;
273 const char* sep = "";
274 for (size_t i = 0; i < LhsSize(); ++i) {
275 ss << sep;
276 for (size_t j = 0; j < RhsSize(); ++j) {
277 ss << HasEdge(i, j);
278 }
279 sep = ";";
280 }
281 return ss.str();
282 }
283
284 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
285 ::std::ostream* os) const {
286 switch (match_flags()) {
287 case UnorderedMatcherRequire::ExactMatch:
288 if (matcher_describers_.empty()) {
289 *os << "is empty";
290 return;
291 }
292 if (matcher_describers_.size() == 1) {
293 *os << "has " << Elements(1) << " and that element ";
294 matcher_describers_[0]->DescribeTo(os);
295 return;
296 }
297 *os << "has " << Elements(matcher_describers_.size())
298 << " and there exists some permutation of elements such that:\n";
299 break;
300 case UnorderedMatcherRequire::Superset:
301 *os << "a surjection from elements to requirements exists such that:\n";
302 break;
303 case UnorderedMatcherRequire::Subset:
304 *os << "an injection from elements to requirements exists such that:\n";
305 break;
306 }
307
308 const char* sep = "";
309 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
310 *os << sep;
311 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
312 *os << " - element #" << i << " ";
313 } else {
314 *os << " - an element ";
315 }
316 matcher_describers_[i]->DescribeTo(os);
317 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
318 sep = ", and\n";
319 } else {
320 sep = "\n";
321 }
322 }
323 }
324
325 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
326 ::std::ostream* os) const {
327 switch (match_flags()) {
328 case UnorderedMatcherRequire::ExactMatch:
329 if (matcher_describers_.empty()) {
330 *os << "isn't empty";
331 return;
332 }
333 if (matcher_describers_.size() == 1) {
334 *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
335 << " that ";
336 matcher_describers_[0]->DescribeNegationTo(os);
337 return;
338 }
339 *os << "doesn't have " << Elements(matcher_describers_.size())
340 << ", or there exists no permutation of elements such that:\n";
341 break;
342 case UnorderedMatcherRequire::Superset:
343 *os << "no surjection from elements to requirements exists such that:\n";
344 break;
345 case UnorderedMatcherRequire::Subset:
346 *os << "no injection from elements to requirements exists such that:\n";
347 break;
348 }
349 const char* sep = "";
350 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
351 *os << sep;
352 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
353 *os << " - element #" << i << " ";
354 } else {
355 *os << " - an element ";
356 }
357 matcher_describers_[i]->DescribeTo(os);
358 if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
359 sep = ", and\n";
360 } else {
361 sep = "\n";
362 }
363 }
364 }
365
366 // Checks that all matchers match at least one element, and that all
367 // elements match at least one matcher. This enables faster matching
368 // and better error reporting.
369 // Returns false, writing an explanation to 'listener', if and only
370 // if the success criteria are not met.
371 bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
372 const ::std::vector<std::string>& element_printouts,
373 const MatchMatrix& matrix, MatchResultListener* listener) const {
374 bool result = true;
375 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
376 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
377
378 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
379 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
380 char matched = matrix.HasEdge(ilhs, irhs);
381 element_matched[ilhs] |= matched;
382 matcher_matched[irhs] |= matched;
383 }
384 }
385
386 if (match_flags() & UnorderedMatcherRequire::Superset) {
387 const char* sep =
388 "where the following matchers don't match any elements:\n";
389 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
390 if (matcher_matched[mi]) continue;
391 result = false;
392 if (listener->IsInterested()) {
393 *listener << sep << "matcher #" << mi << ": ";
394 matcher_describers_[mi]->DescribeTo(listener->stream());
395 sep = ",\n";
396 }
397 }
398 }
399
400 if (match_flags() & UnorderedMatcherRequire::Subset) {
401 const char* sep =
402 "where the following elements don't match any matchers:\n";
403 const char* outer_sep = "";
404 if (!result) {
405 outer_sep = "\nand ";
406 }
407 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
408 if (element_matched[ei]) continue;
409 result = false;
410 if (listener->IsInterested()) {
411 *listener << outer_sep << sep << "element #" << ei << ": "
412 << element_printouts[ei];
413 sep = ",\n";
414 outer_sep = "";
415 }
416 }
417 }
418 return result;
419 }
420
421 bool UnorderedElementsAreMatcherImplBase::FindPairing(
422 const MatchMatrix& matrix, MatchResultListener* listener) const {
423 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
424
425 size_t max_flow = matches.size();
426 if ((match_flags() & UnorderedMatcherRequire::Superset) &&
427 max_flow < matrix.RhsSize()) {
428 if (listener->IsInterested()) {
429 *listener << "where no permutation of the elements can satisfy all "
430 "matchers, and the closest match is "
431 << max_flow << " of " << matrix.RhsSize()
432 << " matchers with the pairings:\n";
433 LogElementMatcherPairVec(matches, listener->stream());
434 }
435 return false;
436 }
437 if ((match_flags() & UnorderedMatcherRequire::Subset) &&
438 max_flow < matrix.LhsSize()) {
439 if (listener->IsInterested()) {
440 *listener
441 << "where not all elements can be matched, and the closest match is "
442 << max_flow << " of " << matrix.RhsSize()
443 << " matchers with the pairings:\n";
444 LogElementMatcherPairVec(matches, listener->stream());
445 }
446 return false;
447 }
448
449 if (matches.size() > 1) {
450 if (listener->IsInterested()) {
451 const char* sep = "where:\n";
452 for (size_t mi = 0; mi < matches.size(); ++mi) {
453 *listener << sep << " - element #" << matches[mi].first
454 << " is matched by matcher #" << matches[mi].second;
455 sep = ",\n";
456 }
457 }
458 }
459 return true;
460 }
461
462 } // namespace internal
463 } // namespace testing