/
match.clj
2146 lines (1797 loc) · 61.1 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])
(:use [clojure.core.match.protocols])
(:require [clojure.set :as set])
(:import [java.io Writer]
[clojure.core.match.protocols IExistentialPattern IPseudoPattern]))
;; =============================================================================
;; # 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_
;;
;; ============================================
;; # 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}
*clojurescript* false)
(def ^{:dynamic true} *line*)
(def ^{:dynamic true} *locals* nil)
(def ^{:dynamic true} *warned*)
(def ^{:dynamic true
:doc "Allow map matching syntax to check for IMatchLookup"}
*match-lookup* false)
(def ^{:dynamic true
:doc "Default vector type. Can be rebound allowing emission of
custom inline code for vector patterns, for example
type-hinted primitive array operations"}
*vector-type* ::vector)
(def ^{:dynamic true
:doc "In the presence of recur we cannot apply code size optimizations"}
*recur-present* false)
(def ^{:dynamic true
:doc "Flag to optimize performance over code size."}
*no-backtrack* false)
(def ^{:doc "Pre-allocated exception used for backtracing"}
backtrack (Exception. "Could not find match."))
(defn backtrack-expr []
(if *clojurescript*
`(throw cljs.core.match/backtrack)
`(throw clojure.core.match/backtrack)))
(defn backtrack-sym []
(if *clojurescript*
'cljs.core.match/backtrack
'clojure.core.match/backtrack))
(def ^{:dynamic true} *backtrack-stack* ())
(def ^{:dynamic true} *root* true)
(defn warn [msg]
(when (not @*warned*)
(binding [*out* *err*]
(println "WARNING:"
(str *ns* ", line " *line* ":")
msg))
(reset! *warned* true)))
(defn get-loop-locals []
(let [LOOP_LOCALS clojure.lang.Compiler/LOOP_LOCALS]
(mapcat
(fn [b]
(let [name (.sym ^clojure.lang.Compiler$LocalBinding b)]
[name name]))
(when (bound? LOOP_LOCALS)
@LOOP_LOCALS))))
;; =============================================================================
;; # 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 ::not-found))
([m k not-found] (val-at m k not-found)))
(defn val-at-expr [& args]
(if *clojurescript*
`(get ~@args)
;;If not ClojureScript, defer to val-at*
`(if (instance? clojure.lang.ILookup ~(first args))
(get ~@args)
(val-at* ~@args))))
;; =============================================================================
;; # Vector Pattern Interop
;;
;; Vectors patterns can generate code specialized on type. This is
;; useful for generating optimal code for data like primitive arrays
;; and bytes. Defaults for vector are provided, see
;; clojure.core.match.array and clojure.core.match.bits for
;; experiments involving these types.
(defn vector-type [t & r] t)
(defmulti check-size? identity)
(defmulti tag (fn [t] t))
(defmulti test-inline vector-type)
(defmulti test-with-size-inline vector-type)
(defmulti test-with-min-size-inline vector-type)
(defmulti count-inline vector-type)
(defmulti nth-inline vector-type)
(defmulti nth-offset-inline vector-type)
(defmulti subvec-inline vector-type)
(defmulti nthnext-inline vector-type)
(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 (and (class? the-tag)
(.isArray ^Class the-tag))
(.getName ^Class the-tag)
the-tag)]
(vary-meta ocr assoc :tag the-tag)))
(defmethod test-inline ::vector
[t ocr]
(let [the-tag (tag t)
c (cond
(class? the-tag) the-tag
(string? the-tag) (Class/forName the-tag)
(symbol? the-tag) (Class/forName (str the-tag))
:else (throw (Error. (str "Unsupported tag type" the-tag))))]
(cond
(= t ::vector) `(vector? ~ocr)
(and (.isArray ^Class c) *clojurescript*) `(cljs.core/array? ~ocr)
:else `(instance? ~c ~ocr))))
(defmethod test-with-size-inline ::vector
[t ocr size]
`(and ~(test-inline t ocr)
(== ~(count-inline t (with-tag t ocr)) ~size)))
(defmethod test-with-min-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)))
(defmethod nthnext-inline ::vector
([_ ocr n] `(nthnext ~ocr ~n)))
;; =============================================================================
;; # Extensions
;; Pattern matrices are represented with persistent
;; vectors. Operations on pattern matrices require us to move
;; something from the middle of the vector to the front - thus prepend
;; and drop-nth. swap will swap the 0th element with the nth element.
(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 Grouping
;;
;; Used to determine the groupable constructors in a column
(defmulti groupable?
"Determine if two patterns may be grouped together for simultaneous
testing."
(fn [a b] [(::tag a) (::tag b)]))
(defmethod groupable? :default
[a b] (= a b))
;; =============================================================================
;; # Pattern Rows
;;
;; Pattern rows are one line of a matrix. They correspond to one
;; clause in the in the user's original pattern. patterns, action,
;; bindings are accessors.
;;
(declare leaf-bind-expr named-wildcard-pattern?)
(deftype PatternRow [ps action bindings]
Object
(equals [_ other]
(and (instance? PatternRow other)
(= ps (:ps other))
(= action (:action other))
(= bindings (:bindings other))))
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.Associative
(assoc [this k v]
(PatternRow. (assoc ps k v) 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.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(case k
:ps ps
:action action
:bindings bindings
not-found))
clojure.lang.IFn
(invoke [_ n]
(nth ps n))
clojure.lang.IPersistentCollection
(cons [_ x]
(PatternRow. (conj ps x) action bindings))
(equiv [this other]
(.equals this other)))
(defn pattern-row
([ps action]
(pattern-row ps action []))
([ps action bindings]
(let [ps (if (vector? ps) ps (into [] ps))]
(PatternRow. ps action bindings))))
;; NOTE: we don't use map destructuring here because PatternRow is
;; both ISeq and ILookup, but in map destructuring seq? is tested
;; first - David
(defn update-pattern [prow i p]
(pattern-row (assoc (:ps prow) i p) (:action prow) (:bindings prow)))
(defn all-wildcards? [prow]
(every? wildcard-pattern? (:ps prow)))
(defn drop-nth-bind [prow n ocr]
(let [ps (:ps prow)
p (ps n)
action (:action prow)
bind-expr (leaf-bind-expr ocr)
as (-> p meta :as)
bindings (or (:bindings prow) [])
bindings (if as
(conj bindings [as bind-expr])
bindings)
bindings (if (named-wildcard-pattern? p)
(conj bindings [(:sym p) bind-expr])
bindings)]
(pattern-row (drop-nth ps n) 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)))
;; TODO precondition on bindings? see above - Ambrose
(defn leaf-node
([value] (LeafNode. value []))
([value bindings] (LeafNode. value bindings)))
(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
(defrecord FailNode []
INodeCompile
(n-to-clj [this]
(if *recur-present*
`(throw
~(if *clojurescript*
`(js/Error. (str "No match found."))
`(Exception. (str "No match found."))))
(backtrack-expr))))
(defn fail-node []
(FailNode.))
;; -----------------------------------------------------------------------------
;; ## Bind Node
(defrecord BindNode [bindings node]
INodeCompile
(n-to-clj [this]
`(let [~@bindings]
~(n-to-clj node))))
(defn bind-node [bindings node]
(BindNode. bindings node))
;; -----------------------------------------------------------------------------
;; ## Switch Node
(declare to-source)
(defn dag-clause-to-clj [occurrence pattern action]
(let [test (if (instance? clojure.core.match.protocols.IPatternCompile pattern)
(to-source* pattern occurrence)
(to-source pattern occurrence))]
[test (n-to-clj action)]))
(defn catch-error [& body]
(let [err-sym (if *clojurescript* 'js/Error 'Exception)]
`(catch ~err-sym e#
(if (identical? e# ~(backtrack-sym))
(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
~(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 switch-node
([occurrence cases default]
{:pre [(sequential? cases)]}
(SwitchNode. occurrence cases default)))
;; =============================================================================
;; # Pattern Matrix
(defn first-column? [i] (zero? i))
(defn empty-row? [row]
(let [ps (:ps row)]
(and (not (nil? ps))
(empty? ps))))
(defn score-column [i col]
[i (reduce + 0 col)])
(defn width [{rows :rows}]
(if (not (empty? rows))
(count (rows 0))
0))
(defn height [{rows :rows}]
(count rows))
(defn dim [pm]
[(width pm) (height pm)])
(defn empty-matrix? [pm]
(= (dim pm) [0 0]))
(defn column [{rows :rows} i]
(vec (map #(nth % i) rows)))
(defn row [{rows :rows} j]
(nth rows j))
(defn rows [{rows :rows}] rows)
(defn pattern-at [{rows :rows} i j]
((rows j) i))
(defn action-for-row [{rows :rows} j]
(:action (rows j)))
(defn occurrences [pm] (:ocrs pm))
;; Returns bindings usable by leaf-node
(defn row-bindings [f ocrs]
(concat (:bindings f)
(->> (map vector (:ps f) ocrs)
(filter (fn [[p ocr]] (named-wildcard-pattern? p)))
(map (fn [[p ocr]] [(:sym p) (leaf-bind-expr ocr)])))))
(defn existential-pattern? [x]
(instance? IExistentialPattern x))
(defn wildcard-or-existential? [x]
(or (wildcard-pattern? x)
(existential-pattern? x)))
(defn constructors-above? [pm i j]
(every?
(comp not wildcard-or-existential?)
(take j (column pm i))))
;; based on paper we used to check the following
;; (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
(defn pattern-score [pm i j]
(let [p (pattern-at pm i j)]
(cond
(or (wildcard-pattern? p)
(not (constructors-above? pm i j))) 0
(existential-pattern? p) 1
:else 2)))
;; DEAD CODE for now - David
;; (defn useful? [pm j]
;; (some #(useful-p? pm % j)
;; (range (count (row pm j)))))
(defn useful-matrix [pm]
(->> (for [j (range (height pm))
i (range (width pm))]
(pattern-score pm i j))
(partition (width pm))
(map vec)
vec))
(defn necessary-column [pm]
(->> (apply map vector (useful-matrix pm))
(map-indexed score-column)
(reduce
(fn [[col score :as curr]
[ocol oscore :as cand]]
(if (> oscore score) cand curr))
[0 0])
first))
(defn select [pm]
(swap pm (necessary-column pm)))
(declare default-specialize-matrix)
(defn specialize
([matrix]
(specialize matrix (ffirst (rows matrix))))
([matrix p]
(if (satisfies? ISpecializeMatrix p)
(specialize-matrix p matrix)
(default-specialize-matrix p matrix))))
(defn pseudo-pattern? [x]
(instance? IPseudoPattern x))
(defn pseudo-patterns [matrix i]
(filter pseudo-pattern? (column matrix i)))
(defn column-splitter [col]
(let [f (first col)
[top bottom] (split-with #(groupable? f %) (rest col))]
[(cons f top) bottom]))
(declare pattern-matrix compile)
(defn return-split [S D]
(if *recur-present*
(if (and (empty-matrix? D) (seq *backtrack-stack*))
[S (peek *backtrack-stack*) *backtrack-stack*]
[S D (conj *backtrack-stack* D)])
[S D]))
(defn matrix-splitter [matrix]
(let [rows (rows matrix)
n (count (first (column-splitter (map first rows))))
ocrs (occurrences matrix)
S (pattern-matrix (take n rows) ocrs)
D (pattern-matrix (drop n rows) ocrs)]
(return-split S D)))
(defn group-rows [cs rows]
(reduce
(fn [res row]
(let [[c rows] (peek res)
c' (first row)]
(if (groupable? c c')
(conj (pop res) [c (conj rows row)])
(conj res [c' [row]]))))
[[(first cs) [(first rows)]]] (rest rows)))
(declare literal-pattern?)
(defn non-local-literal-pattern? [p]
(and (literal-pattern? p)
(not (-> p :l meta :local))))
(defn literal-case-matrix-splitter [matrix]
(let [ocrs (occurrences matrix)
rows (rows matrix)
lrows (loop [rows (seq rows) res [] lits #{}]
;; a bit hacky but lit patterns hash differently we
;; store the literal value directly in lits set
(if rows
(let [[p :as row] (first rows)]
(if (and (non-local-literal-pattern? p)
(not (contains? lits (:l p))))
(recur (next rows) (conj res row)
(if (non-local-literal-pattern? p)
(conj lits (:l p))
lits))
res))
res))
S (->> lrows
(group-rows (map first lrows))
(map (fn [[c rows]]
[c (pattern-matrix rows ocrs)]))
vec)
D (pattern-matrix (drop (count lrows) rows) ocrs)]
(return-split S D)))
(defn default-case [matrix]
(if-not (empty-matrix? matrix)
(compile matrix)
(fail-node)))
(defn cases [matrix]
(if (vector? matrix)
;; grouped literal case
(->> matrix
(map (fn [[c m]]
[c (-> m (specialize c) compile)]))
vec)
;; normal case
(let [rows (rows matrix)
c (ffirst rows)]
[[c (-> matrix (specialize c) compile)]])))
(defn expression? [ocr]
(contains? (meta ocr) :ocr-expr))
(defn bind-variables [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))
(defn root-bind-node [matrix]
(let [ocrs (occurrences matrix)
node (compile matrix)]
(if (some expression? ocrs)
(bind-node (bind-variables ocrs) node)
node)))
;; -----------------------------------------------------------------------------
;; # 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"
[]
(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 [f (first rows)
a (:action f)
bs (:bindings f)]
;; FIXME: 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]
(let [f (first rows)
a (:action f)
bs (row-bindings f ocrs)]
(leaf-node a bs)))
;; if the first pattern in the first column is a
;; pseudo-pattern, expand until it isn't, looking at
;; any rows beyond the first causes problems for
;; fn application pattern
;; TODO: col is always ZERO - this is confusing
;; that it takes col as an argument, fix - David
(defn expand-matrix [matrix col]
(loop [matrix matrix]
(let [p (first (column matrix col))]
(if (pseudo-pattern? p)
(recur (specialize matrix p))
matrix))))
(defn split-matrix [matrix]
(matrix-splitter matrix)
#_(if (non-local-literal-pattern? (ffirst (rows matrix)))
;; literal testing based on equality can do w/o
;; backtracking for all adjacent literal ctors in a column
(literal-case-matrix-splitter matrix)
(matrix-splitter 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"
[matrix col ocrs]
(let [expanded (expand-matrix matrix col)
ocrs (occurrences expanded)
[S D :as split] (split-matrix expanded)]
(if-not *recur-present*
(switch-node (ocrs col)
(cases S)
(default-case D))
(let [new-stack (last split)]
(switch-node (ocrs col)
(if-not (identical? *backtrack-stack* new-stack)
(binding [*backtrack-stack* new-stack]
(cases S))
(cases S))
(if (and (seq *backtrack-stack*)
(identical? (peek *backtrack-stack*) D))
(binding [*backtrack-stack* (pop *backtrack-stack*)]
(default-case D))
(default-case D)))))))
(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"
[matrix col]
(compile (swap matrix col)))
;; Return a column number of a column which contains at least
;; one non-wildcard constructor
(defn choose-column [matrix]
(necessary-column matrix))
(defn compile [{:keys [rows ocrs] :as pm}]
(cond
*root*
(binding [*root* false]
(root-bind-node pm))
(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 pm)]
(if (first-column? col)
(first-column-chosen-case pm col ocrs)
(other-column-chosen-case pm col)))))
(defrecord PatternMatrix [rows ocrs]
IVecMod
(drop-nth [_ i]
(let [nrows (vec (map #(drop-nth % i) rows))]
(PatternMatrix. nrows ocrs)))
;; Swap column number idx with the first column
(swap [_ idx]
(let [nrows (vec (map #(swap % idx) rows))]
(PatternMatrix. nrows (swap ocrs idx)))))
(defn pattern-matrix [rows ocrs]
(let [rows (if (vector? rows) rows (into [] rows))
ocrs (if (vector? ocrs) ocrs (into [] ocrs))]
(PatternMatrix. rows ocrs)))
;; =============================================================================
;; ## Default Matrix Specialization
;; NOTE: not sure why we need groupable? here for this to work - David
(defn default-specialize-matrix [p matrix]
(let [rows (rows matrix)
ocrs (occurrences matrix)
focr (first ocrs)
nrows (->> rows
(map #(drop-nth-bind % 0 focr))
vec)
nocrs (drop-nth ocrs 0)]
(pattern-matrix nrows nocrs)))
;; =============================================================================
;; # Patterns
;;
;; -----------------------------------------------------------------------------
;; ## Wildcard Pattern
;;
;; A wildcard pattern accepts any value.
;;
;; In practice, the DAG compilation eliminates any wildcard patterns.
(deftype WildcardPattern [sym named _meta]
Object
(equals [_ other]
(and (instance? WildcardPattern other)
(if named
(= sym (:sym other))
(not (:named other)))))
clojure.lang.IObj
(withMeta [_ new-meta]
(WildcardPattern. sym named new-meta))
(meta [_]
_meta)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(case k
:sym sym
:named named
not-found)))
(defn wildcard-pattern
([] (wildcard-pattern '_))
([sym]
{:pre [(symbol? sym)]}
(if (= sym '_)
(WildcardPattern. (gensym) false nil)
(WildcardPattern. sym true 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]
(and (instance? WildcardPattern x) (:named x)))
(defmethod print-method 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]
Object
(toString [_]
(if (nil? l)
"nil"
(pr-str l)))
(equals [_ other]
(and (instance? LiteralPattern other) (= l (:l other))))
clojure.lang.IObj
(meta [_] _meta)
(withMeta [_ new-meta]
(LiteralPattern. l new-meta))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(case k
:l l
::tag ::literal
not-found))
IPatternCompile
(to-source* [this ocr]
(cond
(= l ())
`(empty? ~ocr)
(and (symbol? l) (not (-> l meta :local)))
`(= ~ocr '~l)
(and *clojurescript*
(or (number? l) (string? l)
(true? l) (false? l)
(nil? l)))
`(identical? ~ocr ~l)
(and *clojurescript* (keyword? l))
`(cljs.core/keyword-identical? ~ocr ~l)
:else `(= ~ocr ~l))))
(defn literal-pattern [l]
(LiteralPattern. l (meta l)))
(defn literal-pattern? [x]
(instance? LiteralPattern x))
(defmethod print-method 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? rest-pattern? seq-pattern)
(defn specialize-seq-pattern-rest-row [focr row]
(let [p (first row)
p (if (seq-pattern? p)
(:p (first (:s p))) ;; unwrap rest pattern
(wildcard-pattern))]
(prepend (drop-nth-bind row 0 focr) p)))
(defn specialize-seq-pattern-rest-matrix [rows focr]
(->> rows
(map (partial specialize-seq-pattern-rest-row focr))
vec))
(defn seq-pattern-matrix-rest-ocrs [ocrs focr] ocrs)
(defn specialize-seq-pattern-row [focr row]
(let [p (first row)
[h t] (if (seq-pattern? p)
(let [[h & t] (:s p)
t (cond
(empty? t) (literal-pattern ())
(rest-pattern? (first t)) (:p (first t))
:else (seq-pattern t))]
[h t])
[(wildcard-pattern) (wildcard-pattern)])]
(reduce prepend (drop-nth-bind row 0 focr) [t h])))
(defn specialize-seq-pattern-matrix [rows focr]
(->> rows
(map (partial specialize-seq-pattern-row focr))
vec))
(defn seq-pattern-matrix-ocrs [ocrs focr]
(let [seq-sym (or (-> focr meta :seq-sym) focr)
sym-meta {:occurrence-type :seq
:seq-sym focr}
hsym (gensym (str (name seq-sym) "_head__"))
hsym (with-meta hsym
(assoc sym-meta :bind-expr `(first ~focr)))
tsym (gensym (str (name seq-sym) "_tail__"))
tsym (with-meta tsym
(assoc sym-meta :bind-expr `(rest ~focr)))]
(into [hsym tsym] (drop-nth ocrs 0))))