-
Notifications
You must be signed in to change notification settings - Fork 21
/
core.cljc
595 lines (539 loc) · 21.8 KB
/
core.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
(ns matcher-combinators.core
(:require [clojure.math.combinatorics :as combo]
[clojure.pprint]
[clojure.spec.alpha :as s]
[matcher-combinators.model :as model]
[matcher-combinators.result :as result]
[matcher-combinators.utils :as utils]))
(defprotocol Matcher
"For internal use. Type-specific implementations for finding matchers for
expected values and matching them against expected values."
(-matcher-for
[expected]
[expected t->m]
"Do not call directly. Implementation for matcher-combinators.matchers/matcher-for.")
(-base-name [this]
"The name of the matcher as a symbol")
(-match [this actual]
"Do not call directly. Implementation for matcher-combinators.core/match."))
(defn match
"For internal use. Returns a map indicating whether the `actual` value matches `expected`.
`expected` can be the expected value, a matcher, or a predicate fn of actual.
Return map includes the following keys:
- :matcher-combinators.result/type - either :match or :mismatch
- :matcher-combinators.result/value - the actual value with mismatch annotations.
Only present when :match/result is :mismatch"
[expected actual]
(-match expected actual))
(s/fdef indicates-match?
:args (s/cat :match-result ::result/result)
:ret boolean?)
(defn indicates-match?
"Returns true if match-result (the map returned by `(match expected actual)`) indicates a match."
[match-result]
(= :match (::result/type match-result)))
(defn
^{:deprecated true
:doc "DEPRECATED! Use `indicates-match?` instead."}
match?
[match-result]
(println (str "DEPRECATION NOTICE: matcher-combinators.core/match? is deprecated.\n"
" Use matcher-combinators.core/indicates-match? instead."))
(indicates-match? match-result))
(defn matcher? [x]
(satisfies? Matcher x))
(defn- value-match [expected actual]
(cond
(= ::missing actual) {::result/type :mismatch
::result/value (model/->Missing expected)
::result/weight 1}
(= expected actual) {::result/type :match
::result/value actual
::result/weight 0}
:else {::result/type :mismatch
::result/value (model/->Mismatch expected actual)
::result/weight 1}))
(defrecord Value [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [_ actual]
(value-match expected actual))
(-base-name [_] 'equals))
(defn- validate-input
([expected actual pred matcher-name type]
(validate-input expected actual pred pred matcher-name type))
([expected actual expected-pred actual-pred matcher-name type]
(cond
(= actual ::missing)
{::result/type :mismatch
::result/value (model/->Missing expected)
::result/weight 1}
(not (expected-pred expected))
{::result/type :mismatch
::result/value (model/->InvalidMatcherType
(str "provided: " expected)
(str matcher-name
" should be called with 'expected' argument of type: "
type))
::result/weight 1}
(not (actual-pred actual))
{::result/type :mismatch
::result/value (model/->Mismatch expected actual)
::result/weight 1}
:else
nil)))
(defn- regex? [value]
#?(:clj (instance? java.util.regex.Pattern value)
:cljs (regexp? value)))
(def regex-type
#?(:clj "java.util.regex.Pattern"
:cljs "RegExp"))
(defrecord Regex [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input expected actual regex? (constantly true) (-base-name this) regex-type)]
issue
(try
(if-let [match (re-find expected actual)]
{::result/type :match
::result/value match
::result/weight 0}
{::result/type :mismatch
::result/value (model/->Mismatch expected actual)
::result/weight 1})
(catch #?(:clj ClassCastException, :cljs js/Error) _
{::result/type :mismatch
::result/value (model/->InvalidMatcherType
(str "provided: " actual)
(str "regex " (print-str expected) " can't match 'expected' argument of type: "
(type actual)))
::result/weight 1}))))
(-base-name [_] 'regex))
(defrecord Absent []
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [_this _actual]
;; `Absent` should never be matched against directly. That happening means
;; it wasn't used in the context of a map
{::result/type :mismatch
::result/value (model/->InvalidMatcherContext
"`absent` matcher should only be used as the value in a map")
::result/weight 1})
(-base-name [_] 'absent))
(defmethod clojure.pprint/simple-dispatch Absent [absent]
(print (-base-name absent)))
(defrecord InvalidType [provided matcher-name type-msg]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [_this _actual]
{::result/type :mismatch
::result/value (model/->InvalidMatcherType
(str "provided: " provided)
(str matcher-name
" should be called with 'expected' argument of type: "
type-msg))
::result/weight 1})
(-base-name [_] (symbol matcher-name)))
(defn- find-unexpected [expected-map key]
(when-let [[k v] (find expected-map key)]
(when-not (= Absent (type v)) [k v])))
(defn- match-kv [actual [key matcher]]
(if (= Absent (type matcher))
(if-let [[k v] (find actual key)]
[key {::result/type :mismatch
::result/value (model/->Unexpected v)
::result/weight 1}]
nil)
[key (match matcher (get actual key ::missing))]))
(defn- compare-maps [expected actual unexpected-handler allow-unexpected?]
(let [entry-results (->> expected
(map (partial match-kv actual))
(filter identity))
unexpected-entries (keep (fn [[key val]]
(when-not (find-unexpected expected key)
[key (unexpected-handler val)]))
actual)]
(if (and (every? (comp indicates-match? second) entry-results)
(or allow-unexpected? (empty? unexpected-entries)))
{::result/type :match
::result/value actual
::result/weight 0}
(let [mismatch-val (->> entry-results
(map (fn [[key match-result]] [key (::result/value match-result)]))
(concat unexpected-entries)
(into actual))
weight (->> entry-results
(map second)
(reduce (fn [acc-weight {::result/keys [weight]}] (+ acc-weight weight))
(if allow-unexpected? 0 (count unexpected-entries))))]
{::result/type :mismatch
::result/value mismatch-val
::result/weight weight}))))
(def ^:private map-like?
"Returns true if v is associative, but not sequential. This lets us
support map-like structures like Datomic EntityMaps without trying
to compare maps to vectors (which are associative and sequential)."
(every-pred associative? (complement sequential?)))
(defrecord EmbedsMap [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input expected actual map? map-like? (-base-name this) "map")]
issue
(compare-maps expected actual identity true)))
(-base-name [_] 'embeds))
(defrecord EqualsMap [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input expected actual map? (-base-name this) "map")]
issue
(compare-maps expected actual model/->Unexpected false)))
(-base-name [_] 'equals))
(defrecord EqualsRecord [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input expected actual record? map? (-base-name this) "record")]
issue
(if (= (type expected) (type actual))
(match (->EqualsMap expected) actual)
{::result/type :mismatch
::result/value (model/->TypeMismatch expected actual)
::result/weight 1})))
(-base-name [_] 'equals))
(defn- type-preserving-mismatch [base-list values]
(let [lst (into base-list values)]
(if (vector? base-list)
lst
(reverse lst))))
(def ^:private unexpected-matcher
(reify Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [_this actual]
{::result/type :mismatch
::result/value (model/->Unexpected actual)
::result/weight 1})
(-base-name [_] 'unexpected)))
(defrecord ViaMatcher [transform-actual-fn expected]
Matcher
(-matcher-for [_this] (-matcher-for expected))
(-matcher-for [_this x] (-matcher-for expected x))
(-match [_ actual]
(let [transformed (try (transform-actual-fn actual)
(catch #?(:clj Exception :cljs js/Error) e e))]
(if (instance? #?(:clj Exception :cljs js/Error) transformed)
{::result/type :mismatch
::result/value (model/->Mismatch (list 'via (-> transform-actual-fn str symbol) expected) actual)
::result/weight 1}
(match expected transformed))))
(-base-name [_] (-base-name expected)))
(defn- normalize-inputs-length
"Modify the matchers and actuals sequences to match in length.
When `matchers` is longer, add `missing` elements to `actuals`.
When `actuals` is longer, add unexpected entry matchers to `matchers`."
[matchers actuals]
(let [matchers-count (count matchers)
actuals-count (count actuals)]
(if (< actuals-count matchers-count)
[matchers
(take matchers-count (concat actuals (repeat ::missing)))]
[(take actuals-count (concat matchers (repeat unexpected-matcher)))
actuals])))
(defn- sequence-match [expected actual subseq?]
(let [[matchers
actual-elems] (normalize-inputs-length expected actual)
match-results' (map (fn [matcher actual-element] (match matcher actual-element))
matchers actual-elems)
match-size (if subseq?
(count expected)
(max (count actual) (count expected)))
match-results (take match-size match-results')]
(if (some (complement indicates-match?) match-results)
{::result/type :mismatch
::result/value (type-preserving-mismatch (empty actual) (map ::result/value match-results))
::result/weight (->> match-results
(map ::result/weight)
(reduce + 0))}
{::result/type :match
::result/value actual
::result/weight 0})))
(defrecord EqualsSeq [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input
expected actual sequential? (-base-name this) "sequential")]
issue
(sequence-match expected actual false)))
(-base-name [_] 'equals))
(defrecord SeqOf [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input expected actual any? sequential? (-base-name this) "sequential")]
issue
(if (seq actual)
(sequence-match (repeat (count actual) expected) actual false)
{::result/type :mismatch
::result/value (model/->Mismatch "seq-of expects a non-empty sequence" actual)
::result/weight 1})))
(-base-name [_] 'seq-of))
(defn- matched-successfully? [unmatched elements subset?]
(or (and subset? (empty? unmatched))
(and (not subset?) (empty? unmatched) (empty? elements))))
(defn- residual-matching-weight [matchers elements]
(reduce (fn [w {::result/keys [weight]}] (+ w weight))
0
(map match matchers elements)))
(defn- matches-in-any-order? [unmatched elements subset? matching]
(if (or (empty? unmatched) (empty? elements))
(let [matched? (matched-successfully? unmatched elements subset?)]
{:matched? matched?
:unmatched unmatched
:weight (if matched? 0 (residual-matching-weight unmatched elements))
:elements (concat (map second matching) elements)
:matched (map first matching)})
(let [[matcher & unmatched-rest] unmatched
matching-elem (utils/find-first #(indicates-match? (match matcher %))
elements)]
(if (nil? matching-elem)
{:matched? false
:unmatched unmatched
:weight (residual-matching-weight unmatched elements)
:elements (concat (map second matching) elements)
:matched (map first matching)}
(recur unmatched-rest
(utils/remove-first #(= matching-elem %) elements)
subset?
(conj matching [matcher matching-elem]))))))
(defn- better-mismatch? [best candidate]
(let [best-matched (-> best :matched count)
candidate-matched (-> candidate :matched count)
candidate-weight (:weight candidate)
best-weight (:weight best)]
(and (>= candidate-matched best-matched)
(<= candidate-weight best-weight))))
(defn- matched-or-best-matchers [elements subset?]
(fn [best matchers]
(let [{:keys [matched?] :as result} (matches-in-any-order? matchers elements subset? [])]
(cond
matched? (reduced ::match-found)
(better-mismatch? best result) result
:else best))))
(defn- match-all-permutations [expected elements subset?]
(let [[matchers elements] (if subset?
[expected elements]
(normalize-inputs-length expected elements))
matcher-perms (combo/permutations matchers)
find-best-match (matched-or-best-matchers elements subset?)
result (reduce find-best-match
{:matched []
:weight #?(:clj Integer/MAX_VALUE
:cljs (.-MAX_SAFE_INTEGER js/Number))
:elements elements
:unmatched matchers}
matcher-perms)]
(if (= ::match-found result)
{::result/type :match
::result/value elements
::result/weight 0}
(match (->EqualsSeq (concat (:matched result)
(:unmatched result)))
(:elements result)))))
(defn- match-any-order [expected actual subset?]
(if-not (sequential? actual)
{:result/type :mismatch
:result/value (model/->Mismatch expected actual)
:result/weight 1}
(match-all-permutations expected actual subset?)))
(defrecord InAnyOrder [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input
expected actual sequential? (-base-name this) "sequential")]
issue
(match-any-order expected actual false)))
(-base-name [_] 'in-any-order))
(defn- matchable-set?
"Clojure's set functions expect clojure.lang.IPersistentSet, but
matching works just fine with java.util.Set as well."
[s]
#?(:clj (or (set? s) (instance? java.util.Set s))
:cljs (set? s)))
(defrecord SetEquals [expected accept-seq?]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (if accept-seq?
(validate-input expected
actual
#(or (matchable-set? %) (sequential? %))
matchable-set?
(-base-name this)
"set or sequential")
(validate-input expected
actual
matchable-set?
(-base-name this)
"set"))]
issue
(let [{::result/keys [type value weight]} (match-any-order
(vec expected) (vec actual) false)]
{::result/type type
::result/value (set value)
::result/weight weight})))
(-base-name [_] (if accept-seq? 'set-equals 'equals)))
(defrecord Prefix [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input
expected actual sequential? (-base-name this) "sequential")]
issue
(sequence-match expected actual true)))
(-base-name [_] 'prefix))
(defrecord EmbedsSeq [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input
expected actual sequential? (-base-name this) "sequential")]
issue
(match-any-order expected actual true)))
(-base-name [_] 'embeds))
(defrecord SetEmbeds [expected accept-seq?]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (if accept-seq?
(validate-input expected
actual
#(or (matchable-set? %) (sequential? %))
matchable-set?
(-base-name this)
"set or sequential")
(validate-input expected
actual
matchable-set?
(-base-name this)
"set"))]
issue
(let [{::result/keys [type value weight]} (match-any-order
(vec expected) (vec actual) true)]
{::result/type type
::result/value (set value)
::result/weight weight})))
(-base-name [_] (if accept-seq? 'set-embeds 'embeds)))
(defrecord PredMatcher [pred desc]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(cond
(= actual ::missing)
{::result/type :mismatch
::result/value (model/->Missing desc)
::result/weight 1}
(pred actual)
{::result/type :match
::result/value actual
::result/weight 0}
:else
{::result/type :mismatch
::result/value (model/->Mismatch desc actual)
::result/weight 1}))
(-base-name [_] 'predicate))
(defrecord AnyOf [matchers]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(reduce (fn [min-mismatch-weight matcher]
(if (= ::end matcher)
{::result/type :mismatch
::result/value (model/->Mismatch (concat ['any-of] matchers) actual)
::result/weight min-mismatch-weight}
(let [result (match matcher actual)]
(if (indicates-match? result)
(reduced {::result/type :match
::result/value actual
::result/weight 0})
(min (::result/weight result)
min-mismatch-weight)))))
#?(:clj Integer/MAX_VALUE
:cljs (.-MAX_SAFE_INTEGER js/Number))
(conj (into [] matchers) ::end)))
(-base-name [_] 'any-of))
(defrecord AllOf [matchers]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(reduce (fn [_acc matcher]
(if (= ::end matcher)
{::result/type :match
::result/value actual
::result/weight 0}
(let [result (match matcher actual)]
(when-not (indicates-match? result)
(reduced
{::result/type :mismatch
::result/value (model/->Mismatch (concat ['all-of] matchers) actual)
;; using just one mismatch weight is potentially not so useful:
::result/weight (::result/weight result)})))))
nil
(conj (into [] matchers) ::end)))
(-base-name [_] 'all-of))
(defn- printable-matcher [matcher]
(try
(if-let [n (-base-name matcher)]
`(~(symbol n) ~(:expected matcher))
matcher)
(catch #?(:clj IllegalArgumentException :cljs js/Error) _e
matcher)))
(defrecord Mismatcher
[expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(let [{::result/keys [type weight] :as result} (match expected actual)]
(if (= :match type)
{::result/type :mismatch
::result/value (model/->ExpectedMismatch
(printable-matcher expected)
actual)
::result/weight weight}
{::result/type :match
::result/value actual
::result/weight 0})))
(-base-name [_] 'mismatch))
(defrecord CljsUriEquals [expected]
Matcher
(-matcher-for [this] this)
(-matcher-for [this _] this)
(-match [this actual]
(if-let [issue (validate-input
expected actual uri? (-base-name this) "goog.Uri")]
issue
(value-match (.toString expected)
(.toString actual))))
(-base-name [_] 'equals))