/
match.clj
1602 lines (1365 loc) · 54.4 KB
/
match.clj
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns clojure.core.match
(:refer-clojure :exclude [compile])
(:require [clojure.set :as set])
(:import [java.io Writer]))
;; # Introduction
;;
;; This namespace contains an implementation of closed pattern matching. It uses
;; an algorithm based on Luc Maranget's paper "Compiling Pattern Matching to Good Decision Trees".
;;
;; There are three main steps to this implementation:
;;
;; 1. *Converting Clojure syntax to a Pattern Matrix*:
;; The function `emit-matrix` does this work.
;; A Pattern Matrix is represented by PatternMatrix.
;;
;; 2. *Compiling the Pattern Matrix to a Directed Acyclic Graph*:
;; The function `compile` does this work. This step
;; is where Maranget's algorithm is implemented.
;;
;; 3. *Converting the DAG to Clojure code*:
;; This is mostly a 1-1 conversion. See function `executable-form`.
;;
;; # Nomenclature
;;
;; * x and y are called _occurrences_
;; * 1, 2, 3 and 4 are _patterns_
;; * [1 2] and [3 4] are _pattern rows_
;; * :a0 and :a1 are _actions_
;;
(comment
(match [x y]
[1 2] :a0
[3 4] :a1))
;; ============================================
;; # Debugging tools
;;
;; These debugging aids are most useful in steps 2 and 3 of compilation.
;;
;; TODO allow these to be set dynamically, at macro-expand time.
;; Maybe match macros could take extra metadata? - Ambrose
(def ^{:dynamic true
:doc "Enable syntax check of match macros"}
*syntax-check* (atom true))
(def ^{:dynamic true
:doc "Enable breadcrumb diagnostics with fail nodes"}
*breadcrumbs* (atom true))
(def ^{:dynamic true
:doc "Enable pattern compile time tracing"}
*trace* (atom false))
(def ^{:dynamic true
:doc "Enable backtracking diagnostics"}
*backtrack-with-errors* (atom false))
(def ^{:dynamic true}
*clojurescript* false)
(def ^{:dynamic true} *line*)
(def ^{:dynamic true} *locals*)
(def ^{:dynamic true} *warned*)
(def ^{:dynamic true} *vector-type* ::vector)
(def ^{:dynamic true} *match-breadcrumbs* [])
(def ^{:dynamic true} *recur-present* false)
(defn set-trace! [b]
(reset! *trace* b))
(defn set-breadcrumbs! [b]
(reset! *breadcrumbs* b))
(def backtrack (Exception. "Could not find match."))
(defn backtrack-expr []
(if *clojurescript*
`(throw 0)
`(throw clojure.core.match/backtrack)))
(defn warn [msg]
(if (not @*warned*)
(do
(binding [*out* *err*]
(println "WARNING:"
(str *ns* ", line " *line* ":")
msg))
(reset! *warned* true))))
(defn trace-matrix [& p]
(when @*trace*
(apply println "TRACE: MATRIX:" p)
(flush)))
(defn trace-dag [& p]
(when @*trace*
(apply println "TRACE: DAG:" p)
(flush)))
;; =============================================================================
;; # Protocols
(defprotocol ISpecializeMatrix
(specialize-matrix [this rows ocrs]))
(defprotocol IPatternContainer
(pattern [this]))
(defprotocol IContainsRestPattern
(contains-rest-pattern? [this]))
(defprotocol IMatchLookup
"Allows arbitrary objects to act like a map-like object when pattern
matched. Avoid extending this directly for Java Beans, see
`match.java/bean-match`."
(val-at* [this k not-found]))
;; =============================================================================
;; # Map Pattern Interop
(extend-type clojure.lang.ILookup
IMatchLookup
(val-at* [this k not-found]
(.valAt this k not-found)))
(defn val-at
([m k] (val-at* m k nil))
([m k not-found] (val-at* m k not-found)))
(defn val-at-expr [& args]
(if *clojurescript*
`(get ~@args)
`(val-at ~@args)))
;; =============================================================================
;; # Vector Pattern Interop
(defmulti check-size? identity)
(defmulti tag (fn [t] t))
(defmulti test-inline (fn [t & r] t))
(defmulti test-with-size-inline (fn [t & r] t))
(defmulti count-inline (fn [t & r] t))
(defmulti nth-inline (fn [t & r] t))
(defmulti nth-offset-inline (fn [t & r] t))
(defmulti subvec-inline (fn ([t & r] t)))
(defmethod check-size? :default
[_] true)
(defmethod tag :default
[t] (throw (Exception. (str "No tag specified for vector specialization " t))))
(defmethod tag ::vector
[_] clojure.lang.IPersistentVector)
(defn with-tag [t ocr]
(let [the-tag (tag t)
the-tag (if (.isArray ^Class the-tag)
(.getName ^Class the-tag)
the-tag)]
(with-meta ocr (assoc (ocr meta) :tag the-tag))))
(defmethod test-inline ::vector
[t ocr] (if (= t ::vector)
`(vector? ~ocr)
`(instance? ~(tag t) ~ocr)))
(defmethod test-with-size-inline ::vector
[t ocr size] `(and ~(test-inline t ocr) (= ~(count-inline t (with-tag t ocr)) ~size)))
(defmethod count-inline ::vector
[_ ocr] `(count ~ocr))
(defmethod nth-inline ::vector
[_ ocr i] `(nth ~ocr ~i))
(defmethod nth-offset-inline ::vector
[t ocr i offset]
(nth-inline t ocr i))
(defmethod subvec-inline ::vector
([_ ocr start] `(subvec ~ocr ~start))
([_ ocr start end] `(subvec ~ocr ~start ~end)))
;; =============================================================================
;; # Extensions and Protocols
;; TODO: consider converting to multimethods to avoid this nonsense - David
(defprotocol INodeCompile
(n-to-clj [this]))
(defprotocol IPatternCompile
(to-source* [this ocr]))
(defprotocol IVecMod
(prepend [this x])
(drop-nth [this n])
(swap [this n]))
(extend-type clojure.lang.IPersistentVector
IVecMod
(prepend [this x]
(into [x] this))
(drop-nth [this n]
(into (subvec this 0 n)
(subvec this (clojure.core/inc n) (count this))))
(swap [this n]
(let [x (nth this n)]
(prepend (drop-nth this n) x))))
;; -----------------------------------------------------------------------------
;; constructor?
(declare wildcard-pattern?)
(defn constructor? [p]
(not (wildcard-pattern? p)))
;; =============================================================================
;; # Pattern Comparison
;;
;; Used to determine the set of constructors presents in a column and the
;; order which they should be considered
;; FIXME: we use 1 instead of -1, this means we probably have a reverse
;; somehwere - David
(defmulti pattern-compare
"Like `clojure.core/compare` but for comparing patterns"
(fn [a b] [(type a) (type b)]))
(defn pattern-equals [a b]
(zero? (pattern-compare a b)))
(defmethod pattern-compare :default
[a b] (if (= (class a) (class b)) 0 1))
;; =============================================================================
;; # Pattern Rows
(defprotocol IPatternRow
(action [this])
(patterns [this])
(update-pattern [this i p])
(bindings [this])
(all-wildcards? [this])
(drop-nth-bind [this n bind-expr])) ;; TODO: needs better name - David
(declare leaf-bind-expr)
(declare named-wildcard-pattern?)
(declare sym)
(deftype PatternRow [ps action bindings]
IPatternRow
(action [_] action)
(patterns [_] ps)
(update-pattern [_ i p]
(PatternRow. (assoc ps i p) action bindings))
(bindings [_] bindings)
(all-wildcards? [this]
(every? wildcard-pattern? ps))
(drop-nth-bind [this n ocr]
(let [p (ps n)
bind-expr (leaf-bind-expr ocr)
bindings (or bindings [])
bindings (if-let [sym (-> p meta :as)]
(conj bindings [sym bind-expr])
bindings)
bindings (if (named-wildcard-pattern? p)
(conj bindings [(sym p) bind-expr])
bindings)]
(PatternRow. (drop-nth ps n) action
bindings)))
IVecMod
(drop-nth [_ n]
(PatternRow. (drop-nth ps n) action bindings))
(prepend [_ x]
(PatternRow. (into [x] ps) action bindings))
(swap [_ n]
(PatternRow. (swap ps n) action bindings))
clojure.lang.Indexed
(nth [_ i]
(nth ps i))
(nth [_ i x]
(nth ps i x))
clojure.lang.ISeq
(first [_] (first ps))
(next [_]
(if-let [nps (next ps)]
(PatternRow. nps action bindings)
(PatternRow. [] action bindings)))
(more [_]
(if (empty? ps)
nil
(let [nps (rest ps)]
(PatternRow. nps action bindings))))
(seq [this]
(seq ps))
(count [_]
(count ps))
clojure.lang.IFn
(invoke [_ n]
(nth ps n))
clojure.lang.IPersistentCollection
(cons [_ x]
(PatternRow. (conj ps x) action bindings)))
(defn ^PatternRow pattern-row
([ps action]
{:pre [(vector? ps)]}
(PatternRow. ps action nil))
([ps action bindings]
{:pre [(vector? ps)]} ;; TODO: what can we expect bindings? (or (nil? bindings) (list? bindings)) ? - Ambrose
(PatternRow. ps action bindings)))
;; =============================================================================
;; # Compilation Nodes
;; -----------------------------------------------------------------------------
;; ## Leaf Node
(defrecord LeafNode [value bindings]
INodeCompile
(n-to-clj [this]
(if (not (empty? bindings))
(let [bindings (remove (fn [[sym _]] (= sym '_))
bindings)]
`(let [~@(apply concat bindings)]
~value))
value)))
(defn ^LeafNode leaf-node
([value] (LeafNode. value []))
([value bindings] (LeafNode. value bindings))) ;; TODO precondition on bindings? see above - Ambrose
(defmulti leaf-bind-expr (fn [ocr] (-> ocr meta :occurrence-type)))
(defmethod leaf-bind-expr :seq
[ocr] (-> ocr meta :bind-expr))
(defmethod leaf-bind-expr ::vector
[ocr] (-> ocr meta :bind-expr))
(defmethod leaf-bind-expr :map
[ocr] (let [m (meta ocr)]
(val-at-expr (:map-sym m) (:key m))))
(defmethod leaf-bind-expr :default
[ocr] ocr)
;; -----------------------------------------------------------------------------
;; ## Fail Node
(defmacro error [& body]
(if *clojurescript*
`(js/Error. ~@body)
`(Exception. ~@body)))
(defrecord FailNode []
INodeCompile
(n-to-clj [this]
(if *recur-present*
(if @*breadcrumbs*
`(throw (error (str "No match found. "
"Followed " ~(count *match-breadcrumbs*) " branches."
" Breadcrumbs: " '~*match-breadcrumbs*)))
`(throw (error (str "No match found."))))
(backtrack-expr))))
(defn ^FailNode fail-node []
(FailNode.))
;; -----------------------------------------------------------------------------
;; ## Bind Node
(defrecord BindNode [bindings node]
INodeCompile
(n-to-clj [this]
`(let [~@bindings]
~(n-to-clj node))))
(defn ^BindNode bind-node [bindings node]
(BindNode. bindings node))
;; -----------------------------------------------------------------------------
;; ## Switch Node
(declare to-source)
(defn dag-clause-to-clj [occurrence pattern action]
(let [test (if (extends? IPatternCompile (class pattern))
(to-source* pattern occurrence)
(to-source pattern occurrence))]
(if @*breadcrumbs*
(binding [*match-breadcrumbs* (conj *match-breadcrumbs* test)]
[test (n-to-clj action)])
[test (n-to-clj action)])))
(defn catch-error [& body]
(if *clojurescript*
`(catch e#
(if (identical? e# 0)
(do
~@body)
(throw e#)))
`(catch Exception e#
(if (identical? e# clojure.core.match/backtrack)
(do
~@body)
(throw e#)))))
(defrecord SwitchNode [occurrence cases default]
INodeCompile
(n-to-clj [this]
(let [clauses (doall (mapcat (partial apply dag-clause-to-clj occurrence) cases))
bind-expr (-> occurrence meta :bind-expr)
cond-expr (if *recur-present*
(doall (concat `(cond ~@clauses)
`(:else ~(n-to-clj default))))
(doall (concat `(cond ~@clauses)
`(:else ~(if @*backtrack-with-errors*
`(throw (Exception. (str "Could not match" ~occurrence)))
(backtrack-expr))))))]
(if *recur-present*
(if bind-expr
`~(doall (concat `(let [~occurrence ~bind-expr]) (list cond-expr)))
`~cond-expr)
(if bind-expr
`(try ~(doall (concat `(let [~occurrence ~bind-expr]) (list cond-expr)))
~(catch-error (n-to-clj default)))
`(try ~cond-expr
~(catch-error (n-to-clj default))))))))
(defn ^SwitchNode switch-node
([occurrence cases default]
{:pre [(sequential? cases)]}
(SwitchNode. occurrence cases default)))
;; =============================================================================
;; # Pattern Matrix
(defn seq-occurrence? [ocr]
(= (-> ocr meta :occurrence-type) :seq))
(defn map-occurrence? [ocr]
(= (-> ocr meta :occurrence-type) :map))
(defprotocol IPatternMatrix
(width [this])
(height [this])
(dim [this])
(specialize [this c rows ocrs])
(compile [this])
(pattern-at [this i j])
(column [this i])
(row [this j])
(rows [this])
(insert-row [this i row])
(insert-rows [this i rows])
(necessary-column [this])
(useful-matrix [this])
(select [this])
(occurrences [this])
(action-for-row [this j]))
(declare empty-matrix?)
(declare useful-p?)
(declare useful?)
;; # Compilation Cases
;;
;; These are analogous to Maranget's Compilation Scheme on page 4, respectively
;; case 1, 2, 2 (also), 3a and 3b.
;;
(defn- empty-rows-case
"Case 1: If there are no pattern rows to match, then matching always fails"
[]
(let [_ (trace-dag "No rows left, add fail-node")]
(fail-node)))
(defn- first-row-empty-case
"Case 2: If the first row is empty then matching always succeeds
and yields the first action."
[rows ocr]
(let [^PatternRow f (first rows)
a (action f)
bs (bindings f)
_ (trace-dag "Empty row, add leaf-node."
"Could not find match for: " ocr
"Action:" a
"Bindings:" bs)]
;; FIXME: wtf f, the first row is an infinite list of nil - David
(leaf-node a bs)))
(defn- first-row-wildcards-case
"Case 2: If the first row is constituted by wildcards then matching
matching always succeeds and yields the first action."
[rows ocrs]
(letfn [(row-bindings
;; Returns bindings usable by leaf-node
[f ocrs]
(let [ps (.ps ^PatternRow f)
wc-syms (map #(sym %) ps)
wc-bindings (map vector wc-syms
(map leaf-bind-expr ocrs))]
(concat (bindings f)
wc-bindings)))]
(let [f (first rows)
a (action f)
bs (row-bindings f ocrs)
_ (trace-dag (str "First row all wildcards, add leaf-node." a bs))]
(leaf-node a bs))))
(declare pseudo-pattern?)
(declare wildcard-pattern)
(declare vector-pattern?)
(declare pattern-matrix)
(defn- first-column-chosen-case
"Case 3a: The first column is chosen. Compute and return a switch/bind node
with a default matrix case"
[this col ocrs]
(letfn [(pseudo-patterns [this i]
(->> (column this i)
(filter pseudo-pattern?)))
(default-matrix
[this]
(let [m (pattern-matrix (into [] (drop-while #(not (wildcard-pattern? (first %)))
(rows this)))
(occurrences this))]
(if-not (empty-matrix? m)
(do (trace-dag "Add specialized matrix on row of wildcards as default matrix for next node")
(compile m))
(do
(trace-dag "Add fail-node as default matrix for next node (specialized matrix empty)")
(fail-node)))))
;; analyze vector patterns, if a vector-pattern containing a rest pattern
;; occurs, drop all previous vector patterns that it subsumes. note this
;; is a bit hard coding that should be removed when get a better sense
;; how to abstract a protocol for this.
(group-vector-patterns [ps]
(-> (reduce (fn [ps p]
(if (and (vector-pattern? p)
(contains-rest-pattern? p))
(conj (drop-while #(pattern-equals p %) ps) p)
(conj ps p)))
() ps)
reverse))
(column-constructors
;; Returns a sorted-set of constructors in column i of matrix this
[this i]
(let [ps (group-vector-patterns (column this i))]
(->> ps
(take-while (comp not wildcard-pattern?))
(apply sorted-set-by (fn [a b] (pattern-compare a b))))))
(switch-clauses
;; Compile a decision trees for each constructor cs and returns a clause list
;; usable by a switch node
[this cs]
(into []
(map (fn [c rows]
(let [s (-> this
(specialize c rows (occurrences this))
compile)]
[c s]))
cs (loop [[c :as cs] (seq cs) grouped [] rows (rows this)]
(if (nil? cs)
grouped
(let [[l r] (split-with #(pattern-equals c (first %)) rows)]
(recur (next cs) (conj grouped l) r)))))))
(switch-or-bind-node [col ocrs clauses default]
(letfn [(expression?
;; Returns true if occurrence ocr is an expression
[ocr]
(contains? (meta ocr) :ocr-expr))
(bind-variables
;; Return bindings usable by bind-node
[ocrs]
(mapcat (fn [ocr]
(let [bind-expr (get (meta ocr) :ocr-expr ::not-found)]
(if (not= bind-expr ::not-found)
[ocr bind-expr]
[ocr ocr])))
ocrs))]
(if (some expression? ocrs)
(let [b (bind-variables ocrs)
o (ocrs col)
n (switch-node o clauses default)
_ (trace-dag "Add bind-node on occurrence " o ", bindings" b)]
(bind-node b n))
(let [o (ocrs col)
_ (trace-dag "Add switch-node on occurrence " o)]
(switch-node o clauses default)))))]
(let [this (reduce (fn [matrix p]
(specialize matrix p (rows matrix) (occurrences matrix)))
this (pseudo-patterns this col))
constrs (column-constructors this col)
clauses (switch-clauses this constrs)
default (default-matrix this)
_ (trace-dag "Column" col ":" constrs)]
(switch-or-bind-node col ocrs clauses default))))
(defn- other-column-chosen-case
"Case 3b: A column other than the first is chosen. Swap column col with the first column
and compile the result"
[this col]
(let [_ (trace-dag "Swap column " col)]
(compile (swap this col))))
;; # Pattern Matrix definition
(declare default-specialize-matrix)
(deftype PatternMatrix [rows ocrs _meta]
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(PatternMatrix. rows ocrs new-meta))
IPatternMatrix
(width [_] (if (not (empty? rows))
(count (rows 0))
0))
(height [_] (count rows))
(dim [this] [(width this) (height this)])
(specialize [this p rows* ocrs*]
(if (satisfies? ISpecializeMatrix p)
(specialize-matrix p rows* ocrs*)
(default-specialize-matrix p rows* ocrs*)))
(column [_ i] (vec (map #(nth % i) rows)))
(compile [this]
(letfn [(choose-column
;; Return a column number of a column which contains at least
;; one non-wildcard constructor
[this]
(let [col (necessary-column this)
_ (trace-dag "Pick column" col "as necessary column.")]
col))
(first-column? [i]
(zero? i))
(empty-row? [row]
(let [ps (patterns row)]
(and (not (nil? ps))
(empty? ps))))]
(cond
(empty? rows) (empty-rows-case)
(empty-row? (first rows)) (first-row-empty-case rows (first ocrs))
(all-wildcards? (first rows)) (first-row-wildcards-case rows ocrs)
:else (let [col (choose-column this)]
(if (first-column? col)
(first-column-chosen-case this col ocrs)
(other-column-chosen-case this col))))))
(pattern-at [_ i j] ((rows j) i))
(row [_ j] (nth rows j))
(necessary-column [this]
(letfn [(score-column [i col]
[i (reduce (fn [score useful]
(if useful
(clojure.core/inc score)
score))
0 col)])]
(first
(->> (apply map vector (useful-matrix this))
(map-indexed score-column)
(reduce (fn [[col score :as curr]
[ocol oscore :as cand]]
(if (> oscore score) cand curr))
[0 0])))))
(useful-matrix [this]
(vec (->> (for [j (range (height this))
i (range (width this))]
(useful-p? this i j))
(partition (width this))
(map vec))))
(select [this]
(swap this (necessary-column this)))
(rows [_] rows)
(insert-row [_ i row]
(PatternMatrix. (into (conj (subvec rows 0 i) row) (subvec rows i))
ocrs
_meta))
(insert-rows [_ i rows]
(PatternMatrix. (into (into (subvec rows 0 i) rows) (subvec rows i))
ocrs
_meta))
(occurrences [_] ocrs)
(action-for-row [_ j]
(action (rows j)))
IVecMod
(drop-nth [_ i]
(PatternMatrix. (vec (map #(drop-nth % i) rows)) ocrs _meta))
;; Swap column number idx with the first column
(swap [_ idx]
(PatternMatrix. (vec (map #(swap % idx) rows))
(swap ocrs idx)
_meta)))
(defn ^PatternMatrix pattern-matrix [rows ocrs]
{:pre [(vector rows)
(vector ocrs)]}
(PatternMatrix. rows ocrs nil))
(defn empty-matrix? [pm]
(= (dim pm) [0 0]))
(defn useful-p? [pm i j]
(let [p (pattern-at pm i j)]
(cond
(constructor? p) (every? #(not (wildcard-pattern? %))
(take j (column pm i)))
;;(wildcard-pattern? p) (not (useful? (drop-nth pm i) j))
;;IMPORTANT NOTE: this calculation is very very slow,
;;we should look at this more closely - David
:else false)))
(defn useful? [pm j]
(some #(useful-p? pm % j)
(range (count (row pm j)))))
;; =============================================================================
;; ## Default Matrix Specialization
;; NOTE: not sure why we need pattern-equals here for this to work - David
(defn default-specialize-matrix [p rows ocrs]
(let [focr (first ocrs)
nrows (->> rows
(filter #(pattern-equals p (first %)))
(map #(drop-nth-bind % 0 focr))
vec)
nocrs (drop-nth ocrs 0)
_ (trace-dag "Perform default matrix specialization on ocr" focr
", new num ocrs: "
(count ocrs) "->" (count nocrs))]
(pattern-matrix nrows nocrs)))
;; =============================================================================
;; # Patterns
;;
;; -----------------------------------------------------------------------------
;; ## Wildcard Pattern
;;
;; A wildcard pattern accepts any value.
;;
;; In practice, the DAG compilation eliminates any wildcard patterns.
(defprotocol IWildcardPattern
(sym [this]))
(deftype WildcardPattern [sym _meta]
IWildcardPattern
(sym [_] sym)
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(WildcardPattern. sym new-meta))
Object
(toString [_]
(str sym)))
(defn ^WildcardPattern wildcard-pattern
([] (WildcardPattern. '_ nil))
([sym]
{:pre [(symbol? sym)]}
(WildcardPattern. sym nil)))
(defn wildcard-pattern? [x]
(instance? WildcardPattern x))
;; Local bindings in pattern matching are emulated by using named wildcards.
;; See clojure.lang.Symbol dispatch for `emit-pattern`
(defn named-wildcard-pattern? [x]
(when (instance? WildcardPattern x)
(not= (.sym ^WildcardPattern x) '_)))
(defmethod print-method WildcardPattern [^WildcardPattern p ^Writer writer]
(.write writer (str "<WildcardPattern: " (.sym p) ">")))
;; -----------------------------------------------------------------------------
;; ## Literal Pattern
;;
;; A literal pattern is not further split into further patterns in the DAG
;; compilation phase.
;;
;; It "literally" matches a given occurrence.
(deftype LiteralPattern [l _meta]
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(LiteralPattern. l new-meta))
IPatternCompile
(to-source* [this ocr]
(cond
(= l ()) `(empty? ~ocr)
(and (symbol? l) (not (-> l meta :local))) `(= ~ocr '~l)
:else `(= ~ocr ~l)))
Object
(toString [_]
(if (nil? l)
"nil"
(str l))))
(defn ^LiteralPattern literal-pattern [l]
(LiteralPattern. l nil))
(defn literal-pattern? [x]
(instance? LiteralPattern x))
(defmethod print-method LiteralPattern [^LiteralPattern p ^Writer writer]
(.write writer (str "<LiteralPattern: " p ">")))
;; -----------------------------------------------------------------------------
;; ## Seq Pattern
;;
;; A Seq Pattern is intended for matching `seq`s.
;;
;; They are split into multiple patterns, testing each element of the seq in order.
;;
(declare seq-pattern?)
(declare rest-pattern?)
(declare seq-pattern)
(deftype SeqPattern [s _meta]
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(SeqPattern. s new-meta))
IPatternCompile
(to-source* [this ocr]
`(or (seq? ~ocr) (sequential? ~ocr)))
Object
(toString [_]
(str s))
ISpecializeMatrix
(specialize-matrix [this rows ocrs]
(let [focr (first ocrs)
nrows (->> rows
(map (fn [row]
(let [p (first row)
[h t] (if (seq-pattern? p)
(let [^SeqPattern p p
[h & t] (.s p)
t (cond
(empty? t) (literal-pattern ())
(rest-pattern? (first t)) (pattern (first t))
:else (seq-pattern t))]
[h t])
[(wildcard-pattern) (wildcard-pattern)])]
(reduce prepend (drop-nth-bind row 0 focr)
[t h]))))
vec)
nocrs (let [seq-ocr focr
seq-sym (or (-> seq-ocr meta :seq-sym) seq-ocr)
sym-meta {:occurrence-type :seq
:seq-sym seq-ocr}
hsym (gensym (str (name seq-sym) "_head__"))
hsym (with-meta hsym
(assoc sym-meta :bind-expr `(first ~seq-ocr)))
tsym (gensym (str (name seq-sym) "_tail__"))
tsym (with-meta tsym
(assoc sym-meta :bind-expr `(rest ~seq-ocr)))]
(into [hsym tsym] (drop-nth ocrs 0)))
_ (trace-dag "SeqPattern specialization on ocr " focr
", new num ocrs"
(count ocrs) "->" (count nocrs))]
(pattern-matrix nrows nocrs))))
(defn ^SeqPattern seq-pattern [s]
{:pre [(sequential? s)
(not (empty? s))]}
(SeqPattern. s nil))
(defn seq-pattern? [x]
(instance? SeqPattern x))
(defmethod print-method SeqPattern [^SeqPattern p ^Writer writer]
(.write writer (str "<SeqPattern: " p ">")))
;; -----------------------------------------------------------------------------
;; ### Rest Pattern
;;
;; A rest pattern represents the case of matching [2 3] in [1 & [2 3]]
;;
;; It is an implementation detail of other patterns, like SeqPattern.
(deftype RestPattern [p _meta]
IPatternContainer
(pattern [_] p)
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(RestPattern. p new-meta))
Object
(toString [_]
p))
(defn ^RestPattern rest-pattern [p]
(RestPattern. p nil))
(defn rest-pattern? [x]
(instance? RestPattern x))
(defmethod print-method RestPattern [^RestPattern p ^Writer writer]
(.write writer (str "<RestPattern: " (.p p) ">")))
;; -----------------------------------------------------------------------------
;; # Map Pattern
;;
;; Map patterns match maps, or any object that satisfies IMatchLookup.
(declare map-pattern?)
(declare guard-pattern)
(defn key-compare [a b]
(if (= (type a) (type b))
(compare a b)
-1))
(deftype MapPattern [m _meta]
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(MapPattern. m new-meta))
IPatternCompile
(to-source* [this ocr]
(if *clojurescript*
`(or (satisfies? cljs.core.ILookup ~ocr))
`(or (instance? clojure.lang.ILookup ~ocr) (satisfies? IMatchLookup ~ocr))))
Object
(toString [_]
(str m " :only " (or (:only _meta) [])))
ISpecializeMatrix
(specialize-matrix [this rows ocrs]
(let [focr (first ocrs)
only? (atom false)
all-keys (->> rows
(remove (comp wildcard-pattern? first))
(map (fn [row]
(let [^MapPattern p (first row)
only (-> p meta :only)]
(when (and (not @only?) (seq only))
(reset! only? true))
[(set (keys (.m p)))
(set only)])))
(reduce concat)
(reduce set/union #{})
(sort key-compare))
wcs (repeatedly wildcard-pattern)
wc-map (zipmap all-keys wcs)
nrows (->> rows
(map (fn [row]
(let [p (first row)
only (seq (-> p meta :only))
ocr-map (if (map-pattern? p)
(let [^MapPattern p p
m (.m p)
[not-found-map wc-map] (if only
[(zipmap all-keys
(repeat (literal-pattern ::not-found)))
(zipmap only wcs)]
[{} wc-map])]