-
Notifications
You must be signed in to change notification settings - Fork 1
/
functional-trees.lisp
1712 lines (1542 loc) · 71.6 KB
/
functional-trees.lisp
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
;;;; functional-trees.lisp --- Tree data structure with functional manipulation
;;;;
;;;; Copyright (C) 2020 GrammaTech, Inc.
;;;;
;;;; This code is licensed under the MIT license. See the LICENSE.txt
;;;; file in the project root for license terms.
;;;;
;;;; This project is sponsored by the Office of Naval Research, One
;;;; Liberty Center, 875 N. Randolph Street, Arlington, VA 22203 under
;;;; contract # N68335-17-C-0700. The content of the information does
;;;; not necessarily reflect the position or policy of the Government
;;;; and no official endorsement should be inferred.
(defpackage :functional-trees
(:nicknames :ft :functional-trees/functional-trees)
(:use :common-lisp :alexandria :iterate :cl-store :bordeaux-threads)
(:import-from :serapeum
:with-item-key-function
:with-two-arg-test
:with-boolean
:def)
(:shadowing-import-from :fset
:@ :do-seq :seq :lookup :alist :size
:unionf :appendf :with :less :splice :insert :removef
;; Shadowed set operations
:union :intersection :set-difference :complement
;; Shadowed sequence operations
:first :last :subseq :reverse :sort :stable-sort
:reduce
:find :find-if :find-if-not
:count :count-if :count-if-not
:position :position-if :position-if-not
:remove :remove-if :remove-if-not :filter
:substitute :substitute-if :substitute-if-not
:some :every :notany :notevery
;; Additional stuff
:identity-ordering-mixin :serial-number
:compare :convert)
(:shadow :subst :subst-if :subst-if-not :assert :mapc :mapcar)
(:shadowing-import-from :alexandria :compose)
(:shadowing-import-from :functional-trees/interval-trees)
(:import-from :uiop/utility :nest)
(:import-from :serapeum :queue :qconc :qpreconc :qlist
:set-hash-table :length< :box :unbox
:with-thunk :-> :lret)
(:import-from :closer-mop
:slot-definition-name
:slot-definition-allocation
:slot-definition-initform
:slot-definition-initargs
:class-slots
:ensure-finalized)
(:import-from :atomics)
(:export :copy :tree-copy
:copy-with-children-alist
:node :child-slots
:child-slot-specifiers
:serial-number
:descendant-map :path
:path-of-node
:rpath-to-node
:path-equalp
:path-equalp-butlast
:path-later-p
:parent
:predecessor
:successor
:children
:children-alist
:children-slot-specifier-alist
:do-tree :mapc :mapcar
:swap
:define-node-class :define-methods-for-node-class
:child-position-if
:child-position
:subst :subst-if :subst-if-not
:with-serial-number-block)
(:documentation
"Prototype implementation of functional trees w. finger objects"))
(in-package :functional-trees)
(defmacro assert (&body body)
;; Copy the body of the assert so it doesn't pollute coverage reports
`(cl:assert ,@(copy-tree body)))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Allocate blocks of serial numbers on a per-thread basis. This
;; solves the problem where parsing in parallel would lead to
;; extremely deep trees that were extremely slow to traverse due to
;; widely-separated serial numbers.
;; Note this is a standard technique in other contexts where serial
;; numbers are used (databases, for example, allocate blocks of
;; serial numbers to workers in this way).
(declaim (type box *serial-number-index*))
(defvar *serial-number-index* (box 0))
(def +serial-number-block-size+ 10000)
(declaim (type (or null box) *current-serial-number-block*))
(defvar *current-serial-number-block* nil)
(defstruct serial-number-block
(end (required-argument :end) :read-only t)
(index (required-argument :index))
(thread (bt:current-thread)))
(-> allocate-serial-number-block () (values serial-number-block &optional))
(defun allocate-serial-number-block ()
(let ((end nil))
(atomics:atomic-update
(unbox *serial-number-index*)
(lambda (idx) (setf end (+ idx +serial-number-block-size+))))
(make-serial-number-block :end end
;; NB The initial index
;; belongs to the last block
;; allocated.
:index (1+ (- end +serial-number-block-size+)))))
(defvar *fallback-block-mapping*
(multiple-value-call #'tg:make-weak-hash-table
:weakness :key
#+sbcl (values :synchronized t)))
(-> allocate-fallback-block () (values box &optional))
(defun allocate-fallback-block ()
"Allocate a serial number block using `*fallback-block-mapping*'."
;; Box the current thread's block, allowing advancing
;; it without having to lock the thread->block hash
;; table again.
(flet ((ensure-box ()
(ensure-gethash (bt:current-thread)
*fallback-block-mapping*
(box nil))))
(declare (inline ensure-box))
(lret ((box
#+sbcl
(sb-ext:with-locked-hash-table (*fallback-block-mapping*)
(ensure-box))
#+ccl (ensure-box)
#-(or sbcl ccl)
(serapeum:synchronized ()
(ensure-box))))
(setf (unbox box) (allocate-serial-number-block)))))
(-> current-serial-number-block () (values box &optional))
(defun current-serial-number-block ()
"Get the (boxed) serial number block for the current thread, creating
or advancing it as necessary."
;; if first call on thread, initialize block
(when (null *current-serial-number-block*)
(setf *current-serial-number-block* (box (allocate-serial-number-block))))
(let ((current-block
(if (eql (bt:current-thread)
(serial-number-block-thread
(unbox *current-serial-number-block*)))
;; This is our block.
*current-serial-number-block*
(allocate-fallback-block))))
;; Advance to a new block if needed.
(when (= (serial-number-block-index (unbox current-block))
(serial-number-block-end (unbox current-block)))
(setf (unbox current-block) (allocate-serial-number-block)))
current-block))
(-> next-serial-number () (values (integer 0) &optional))
(defun next-serial-number ()
"Return the next serial number in the current thread's block"
(let ((current-block (current-serial-number-block)))
(1- (incf (serial-number-block-index (unbox current-block))))))
(defun call/serial-number-block (fn)
(let ((*current-serial-number-block* (current-serial-number-block)))
(funcall fn)))
(defmacro with-serial-number-block ((&key) &body body)
"Run BODY with `*current-serial-number-block*' bound to the current
thread's serial number block, even without a thread-local binding.
Avoids BODY needing to lookup the block in a global table every time
it requests a new serial number."
(with-thunk (body)
`(call/serial-number-block ,body)))
;; ensure that each thread gets its own binding of serial number block
(pushnew '(*current-serial-number-block* . nil)
bt:*default-special-bindings*
:test #'equal)
;; Clear the serial number block when saving an image.
(defun clear-serial-number-block ()
(setf *current-serial-number-block* nil))
(uiop:register-image-dump-hook 'clear-serial-number-block)
(defclass descendant-map-mixin ()
((descendant-map :initarg :descendant-map
:documentation "Map from serial numbers to child slots"))
(:documentation "Mixin for the descendant-map slot"))
(defclass node-identity-ordering-mixin (identity-ordering-mixin) ())
;;; NOTE: We might want to propose a patch to FSet to allow setting
;;; serial-number with an initialization argument.
(defmethod initialize-instance :after
((node node-identity-ordering-mixin)
&key (serial-number nil) &allow-other-keys)
(setf (slot-value node 'serial-number)
(or serial-number (next-serial-number)))
node)
(defclass node (node-identity-ordering-mixin descendant-map-mixin)
((size :reader size
:type (integer 1)
:documentation "Number of nodes in tree rooted here.")
(child-slots :reader child-slots
:initform nil
:allocation :class
:type list ;; of (or symbol cons)
:documentation
"List of child slots with optional arity.
This field should be specified as :allocation :class if defined by a
subclass of `node'. List of either symbols specifying a slot holding
a list of children or a cons of (symbol . number) where number
specifies a specific number of children held in the slot.")
(child-slot-specifiers :reader child-slot-specifiers
:allocation :class
:type list
:documentation "The list CHILD-SLOTS
converted to a list of slot-specifier objects"))
(:documentation "A node in a tree."))
(defclass slot-specifier ()
((class :reader slot-specifier-class
:initarg :class
:documentation "The class to which the slot belongs")
(slot :reader slot-specifier-slot
:initarg :slot
:type symbol
:documentation "The name of the slot")
(arity :reader slot-specifier-arity
:type (integer 0)
:initarg :arity
:documentation "The arity of the slot"))
(:documentation "Object that represents the slots of a class")))
(defmethod convert ((to-type (eql 'node)) (node node) &key)
node)
(declaim (inline descendant-map))
(defun descendant-map (obj)
(slot-value obj 'descendant-map))
(defun make-slot-specifier (&rest args)
(apply #'make-instance 'slot-specifier args))
(defmethod slot-unbound ((class t) (obj node) (slot (eql 'child-slot-specifiers)))
(setf (slot-value obj slot)
(iter (for p in (child-slots obj))
(collecting
(etypecase p
(symbol (make-slot-specifier
:class class :slot p :arity 0))
(cons (make-slot-specifier
:class class :slot (car p)
:arity (or (cdr p) 0))))))))
(defgeneric slot-specifier-for-slot (obj slot &optional error?)
(:documentation "Returns the child slot SLOT in node OBJ. If it is not
the name of a child slot, return NIL if error? is NIL and error if error?
is true (the default.)")
(:method ((obj node) (slot slot-specifier) &optional (error? t))
(when (and (not (eql (slot-specifier-class slot) (class-of obj)))
error?)
(error "Slot specifier class ~a does not match object ~a's class"
(slot-specifier-class slot) obj))
slot)
(:method ((obj node) (slot symbol) &optional (error? t))
(let ((slot-spec (find slot (child-slot-specifiers obj) :key #'slot-specifier-slot)))
(or slot-spec
(when error?
(error "Not a slot in ~a: ~a" obj slot))))))
(declaim (inline slot-spec-slot slot-spec-arity child-list))
(defun slot-spec-slot (slot-spec)
(if (consp slot-spec) (car slot-spec) slot-spec))
(defun slot-spec-arity (slot-spec)
(or (and (consp slot-spec) (cdr slot-spec)) 0))
(defgeneric slot-spec-of-slot (obj slot &optional error?)
(:documentation "Returns the slot spec pair of a slot in OBJ. If ERROR? is
true (the default) signal an error if SLOT is not a child slot of OBJ.
Otherwise, in that case return NIL.")
(:method ((obj node) (slot symbol) &optional (error? t))
(dolist (p (child-slots obj)
(when error? (error "Not a child slot of ~a: ~a" obj slot)))
(etypecase p
(symbol (when (eql p slot) (return p)))
(cons (when (eql (car p) slot) (return p)))))))
;;;; Core functional tree definitions.
(deftype path ()
`(and list (satisfies path-p)))
(defun path-p (list)
(every (lambda (x)
(typecase x
((integer 0) t) ; Index into `children'.
(symbol t) ; Name of scalar child-slot.
((cons (integer 0) ; Non-scalar child-slot w/index.
(cons integer null))
(<= (first x) (second x)))
((cons symbol null) t)
((cons symbol (integer 0)) t)
(t nil)))
list))
(defgeneric path-equalp (path-a path-b)
(:documentation "Are path-a and path-b the same path?")
(:method ((path-a t) (path-b t))
(and (length= path-a path-b)
(every #'path-element-= path-a path-b))))
(defgeneric path-equalp-butlast (path-a path-b)
(:documentation "Are path-a and path-b the same, except possibly
for their last entries?")
(:method ((path-a t) (path-b t))
(path-equalp (butlast path-a) (butlast path-b))))
(defgeneric slot-position-in-node (node slot)
(:method ((node node) (slot symbol))
(cl:position slot (child-slots node) :key #'slot-spec-slot)))
(defmacro cons-0-de ((&rest syms) &body body)
(assert (every #'identity syms))
(assert (every #'symbolp syms))
(assert (length= syms (remove-duplicates syms)))
`(let ,(cl:mapcar (lambda (s)`(,s (cons ,s 0))) syms)
(declare (dynamic-extent ,@syms))
,@body))
(defgeneric path-element-> (node a b)
(:documentation "Ordering function for elements of paths")
(:method ((node t) (a real) (b real))
(> a b))
(:method ((node node) (a cons) (b cons))
(let ((ca (car a))
(cb (car b))
(na (or (cdr a) 0))
(nb (or (cdr b) 0)))
(assert (symbolp ca))
(assert (symbolp cb))
(cond
((eql ca cb) (> na nb))
;; (t (string> (symbol-name ca) (symbol-name cb)))
(t
(> (slot-position-in-node node ca)
(slot-position-in-node node cb)))
)))
(:method ((node t) (a symbol) (b symbol))
(cons-0-de (a b) (path-element-> node a b)))
(:method ((node t) (a symbol) (b t))
(cons-0-de (a) (path-element-> node a b)))
(:method ((node t) (a t) (b symbol))
(cons-0-de (b) (path-element-> node a b)))
(:method ((node t) (a cons) (b real)) nil)
(:method ((node t) (a real) (b cons)) t))
(defgeneric path-element-= (a b)
(:documentation "Equality function for elements of a path, taking
into account the representation of named children")
(:method ((a real) (b real)) (eql a b))
(:method ((a cons) (b real)) nil)
(:method ((a real) (b cons)) nil)
(:method ((a symbol) (b symbol)) (eql a b))
(:method ((a symbol) (b t))
(cons-0-de (a) (path-element-= a b)))
(:method ((a t) (b symbol))
(cons-0-de (b) (path-element-= a b)))
(:method ((a cons) (b cons))
(and (eql (car a) (car b))
(eql (or (cdr a) 0)
(or (cdr b) 0)))))
;;; TODO: determine if this may or should be combined with lexicographic-<
(defgeneric path-later-p (node path-a path-b)
(:documentation "Does PATH-A from NODE represent an NODE path after
PATH-B from NODE? Use this to sort NODE nodes for mutations that perform
multiple operations.")
(:method ((node t) (path-a null) (path-b null)) nil)
(:method ((node node) (path-a null) (path-b null)) nil)
(:method ((node t) (path-a null) (path-b cons)) nil)
(:method ((node node) (path-a null) (path-b cons)) nil)
(:method ((node t) (path-a cons) (path-b null)) t)
(:method ((node node) (path-a cons) (path-b null)) t)
(:method ((node t) (path-a list) (path-b list))
;; Consider longer paths to be later, so in case of nested NODEs we
;; will sort inner one first. Mutating the outer NODE could
;; invalidate the inner node.
(nest (destructuring-bind (head-a . tail-a) path-a)
(destructuring-bind (head-b . tail-b) path-b)
(cond
((path-element-> node head-a head-b) t)
((path-element-> node head-b head-a) nil)
((path-element-= head-a head-b)
(path-later-p (@ node head-a) tail-a tail-b))))))
;;; FIXME: Should we replace this with an explicit deep copy? We
;;; wouldn't be able to re-use `copy-array', `copy-seq', etc but we
;;; could then remove `copy-tree' and just use this generic copy
;;; universally instead. It would also then more closely mimic the
;;; behavior of the `equal?' method defined in GT and FSET.
(defgeneric copy (obj &key &allow-other-keys)
(:documentation "Generic COPY method.") ; TODO: Extend from generic-cl?
(:method ((obj t) &key &allow-other-keys) obj)
(:method ((obj array) &key &allow-other-keys) (copy-array obj))
(:method ((obj hash-table) &key &allow-other-keys) (copy-hash-table obj))
(:method ((obj list) &key &allow-other-keys) (copy-list obj))
(:method ((obj sequence) &key &allow-other-keys) (copy-seq obj))
(:method ((obj symbol) &key &allow-other-keys) (copy-symbol obj)))
(defgeneric copy-with-children-alist (obj children-alist &rest args)
(:documentation "Perform a copy of node OBJ, with children-alist being
used to initialize some children")
(:method ((obj node) (children-alist list) &rest args)
(apply #'copy obj (nconc (mapcan (lambda (p)
(typecase (car p)
(slot-specifier
(list (make-keyword (slot-specifier-slot (car p)))
(if (eql (slot-specifier-arity (car p)) 1)
(cadr p)
(cdr p))))
(t (list (car p) (cdr p)))))
children-alist)
args))))
(defgeneric tree-copy (obj)
(:documentation "Copy method that descends into a tree and copies all
its nodes.")
(:method ((obj t)) obj)
(:method ((obj list)) (cl:mapcar #'tree-copy obj)))
(defmacro define-node-class (name superclasses slots &rest rest)
(flet ((method-options-p (item)
(and (consp item) (eq :method-options (car item)))))
`(progn
(eval-when (:load-toplevel :compile-toplevel :execute)
(defclass ,name ,superclasses
((child-slot-specifiers :allocation :class)
,@slots)
,@(remove-if #'method-options-p rest))
(define-methods-for-node-class ,name
,(cdr (find-if #'method-options-p rest)))))))
;; debug macro
(defmacro dump (&body forms)
`(progn
,@(iter (for form in forms)
(collecting `(format t "~a = ~s~%"
,(format nil "~s" form)
,form)))))
(defvar *node-obj-code* (register-code 45 'node))
(defstore-cl-store (obj node stream)
(let ((*store-class-slots* nil))
(output-type-code *node-obj-code* stream)
(cl-store::store-type-object obj stream)))
(defrestore-cl-store (node stream)
(cl-store::restore-type-object stream))
(define-compiler-macro children (node)
`(locally (declare (notinline children))
(the (values list &optional) (children ,node))))
(defgeneric children (node)
(:documentation "Return all children of NODE.")
(:method ((node node))
(mappend (lambda (slot-spec)
(multiple-value-bind (slot arity)
(etypecase slot-spec
(cons (values (car slot-spec) (cdr slot-spec)))
(symbol (values slot-spec 0)))
(if (eql 1 arity)
(list (slot-value node slot))
(slot-value node slot))))
(child-slots node))))
(defgeneric children-alist (node)
(:documentation "Return an alist mapping child slots
of NODE to their members.")
(:method ((node node))
(cl:mapcar (lambda (slot-spec)
(multiple-value-bind (slot arity)
(etypecase slot-spec
(cons (values (car slot-spec) (cdr slot-spec)))
(symbol (values slot-spec 0)))
(if (eql 1 arity)
(list slot (slot-value node slot))
(cons slot (slot-value node slot)))))
(child-slots node))))
(defgeneric children-slot-specifier-alist (node)
(:documentation "Return an alist mapping child slot specifiers
of NODE to their members")
(:method ((node node))
(cl:mapcar (lambda (ss)
(let ((v (slot-value node (slot-specifier-slot ss))))
(if (eql (slot-specifier-arity ss) 1)
(if v (list ss v) (list ss))
(cons ss v))))
(child-slot-specifiers node))))
(defun expand-children-defmethod (class child-slots)
`(defmethod children ((node ,class))
;; NOTE: For now just append everything together wrapping
;; singleton arity slots in `(list ...)'. Down the line
;; perhaps something smarter that takes advantage of the
;; known size of some--maybe all--slots would be better.
(append ,@(cl:mapcar (lambda (form)
(destructuring-bind (slot . arity)
(etypecase form
(symbol (cons form nil))
(cons form))
(if (and arity (= (the fixnum arity) 1))
`(list (slot-value node ',slot))
`(slot-value node ',slot))))
child-slots))))
(defun store-actual-slot (key actual-slot)
(assert (keywordp key))
(assert (equal (symbol-name key)
(symbol-name actual-slot)))
(assert (not (eql key actual-slot)))
(let ((a (get key 'actual-slot)))
(when (and a (not (eql a actual-slot)))
(error "Keyword ~s corresponds to two different slots: ~s and ~s"
key a actual-slot))
(unless a
(setf (get key 'actual-slot) actual-slot))
actual-slot))
(defun store-actual-slots (slot-names)
(dolist (slot-name slot-names)
(store-actual-slot (make-keyword slot-name) slot-name)))
(defun get-actual-slot (slot)
(etypecase slot
(keyword (or (get slot 'actual-slot)
(error "Keyword ~a does not correspond to an actual slot" slot)))
(symbol slot)))
(defmethod lookup ((obj node) (slot symbol))
(if-let ((actual-slot (and (keywordp slot)
(get-actual-slot slot))))
(slot-value obj actual-slot)
(call-next-method)))
(eval-when (:compile-toplevel :load-toplevel)
(defun slot-setf-expander (node slot-name env)
(nest
(let ((key (make-keyword slot-name))))
(multiple-value-bind (temps vals stores store-form access-form)
(get-setf-expansion node env))
(let ((val-temp (gensym))
(coll-temp (car stores)))
(when (cdr stores)
(error "Too many values required in `setf' of `~a'" slot-name)))
(values temps
(cons key vals)
(list val-temp)
`(let ((,coll-temp (with ,access-form ',key ,val-temp)))
,store-form
,val-temp)
`(lookup ,access-form ',key)))))
;;; TODO -- change this so keywords are handled differently
(defun expand-lookup-specialization (class child-slots)
(let ((child-slot-names
(iter (for cs in child-slots)
(collect (etypecase cs
(symbol cs)
(cons (car cs)))))))
`(progn
;; Storing the actual slot needs to be done as part of the
;; macroexpansion, within an eval-when form, rather than in the
;; macro itself, so the mapping persists beyond compile time.
,@(when child-slot-names
`((store-actual-slots ',child-slot-names)))
,@(unless (subtypep class 'node)
(cl:mapcar (lambda (slot)
`(defmethod lookup
((obj ,class) (key (eql ,(make-keyword slot))))
(slot-value obj ',slot)))
child-slot-names)))))
(defun expand-setf-error-methods (class child-slots)
"Generate (setf <slot>) methods for CLASS that just signal errors
telling the user to use (setf (@ ... :<slot>) ...)"
`(progn
,@(cl:mapcar (lambda (form)
(let ((slot (etypecase form
(symbol form)
(cons (car form)))))
`(defmethod (setf ,slot) ((obj ,class) (value t))
(error "Functional setf to slot ~A of class ~A should be via setf of (@ <obj> ~s)"
',slot ',class ,(make-keyword slot)))))
child-slots)))
(defmacro define-methods-for-node-class (class-name method-options
&environment env)
(let ((class (find-class class-name env)))
(assert class () "No class found for ~s" class-name)
(ensure-finalized class)
(let ((child-slots
(nest (eval)
(slot-definition-initform)
(find-if
(lambda (slot)
(and (eql 'child-slots (slot-definition-name slot))
(eql :class (slot-definition-allocation slot)))))
(class-slots class))))
;; Confirm that all child slots have an initarg that is a keyword
;; of the same name
(let ((slot-defs (class-slots class)))
(iter (for def in slot-defs)
(let ((name (slot-definition-name def)))
(when (member name child-slots)
(let ((desired-initarg (make-keyword name))
(actual-initargs (slot-definition-initargs def)))
(unless (member desired-initarg actual-initargs)
(error "Class ~a does not have initarg ~s for slot ~a"
class-name desired-initarg name)))))))
`(progn
,(unless (member :skip-children-definition method-options)
(expand-children-defmethod class child-slots))
,(expand-lookup-specialization class child-slots)
,(expand-setf-error-methods class child-slots)
))))
(defmethod slot-unbound ((class t) (obj node) (slot-name (eql 'size)))
(setf (slot-value obj 'size)
(reduce #'+ (children obj) :key #'size :initial-value 1)))
;;; NOTE: There should be a way to chain together methods for COPY for
;;; classes and their superclasses, perhaps using the initialization
;;; infrastructure in CL for objects.
(defmethod copy ((node node) &rest keys)
(nest
(compute-descendant-map node)
(apply #'make-instance (class-of node))
(apply #'append keys)
(cl:mapcar (lambda (slot) (list (make-keyword slot) (slot-value node slot))))
(cl:remove-if-not (lambda (slot) (slot-boundp node slot)))
(cl:mapcar #'slot-definition-name)
(remove-if (lambda (slot) (eql :class (slot-definition-allocation slot))))
(class-slots (class-of node))))
;;; Fill in the slot lazily
(defmethod slot-unbound ((class t) (node node) (slot (eql 'descendant-map)))
(let* ((intervals
(iter (for slot-spec in (child-slot-specifiers node))
(let* ((slot (slot-specifier-slot slot-spec))
(val (slot-value node slot)))
(nconcing
(if (listp val)
(iter (for v in val)
(nconcing (add-slot-to-intervals (intervals-of-node v) slot)))
(add-slot-to-intervals (intervals-of-node val) slot))))))
(sn (serial-number node)))
(setf (slot-value node 'descendant-map)
(convert 'ft/it:itree (cons (list (cons sn sn) nil) intervals)))))
(defgeneric intervals-of-node (node)
(:documentation "Compute a fresh list of intervals for the subtree rooted at NODE.")
(:method ((node node))
(ft/it:intervals-of-itree (descendant-map node)))
(:method ((node t)) nil))
(defun add-slot-to-intervals (intervals slot)
"Returns a fresh list of (interval slot) pairs"
(mapcar (lambda (interval) (list interval slot)) intervals))
(defun set-difference/hash (list1 list2)
"Like `set-difference', but use a hash table if the set is large enough.
Duplicates are allowed in both lists."
(cond ((equal list1 list2) nil)
((length< list2 20)
(set-difference list1 list2))
;; Allow duplicates.
(t
(let ((hash-set (set-hash-table list2 :strict nil)))
(remove-if (lambda (x)
(gethash x hash-set))
list1)))))
;;; Fill in the descendant-map field of a node after copy
;;; TODO -- do not fill in the map if the node's size is below
;;; a threshold. Instead, lookups that would use the map would
;;; instead search the subtree directly.
(defgeneric compute-descendant-map (old-node new-node)
(:method ((old-node t) (new-node t)) new-node)
(:method ((old-node node) (new-node node))
(assert (eql (class-of old-node) (class-of new-node)))
(let* ((old-dm (descendant-map old-node))
(differing-child-slot-specifiers
;; The specifiers for the slots on which old-node
;; and new-node differ
(iter (for slot-spec in (child-slot-specifiers new-node))
(let ((slot (slot-specifier-slot slot-spec)))
(unless (eql (slot-value old-node slot)
(slot-value new-node slot))
(collecting slot-spec)))))
(old-sn (serial-number old-node))
(intervals-to-remove (queue `(,old-sn . ,old-sn)))
(new-sn (serial-number new-node))
(intervals-to-add (queue `((,new-sn . ,new-sn)))))
(declare (dynamic-extent intervals-to-remove intervals-to-add))
(iter (for slot-spec in differing-child-slot-specifiers)
(let* ((slot (slot-specifier-slot slot-spec))
(old (slot-value old-node slot))
(new (slot-value new-node slot)))
(cond
((and (listp old) (listp new))
(let ((removed-children (set-difference/hash old new))
(added-children (set-difference/hash new old)))
;; (format t "Removed children: ~a~%" removed-children)
;; (format t "Added children: ~a~%" added-children)
(iter (for removed-child in removed-children)
(qconc intervals-to-remove (intervals-of-node removed-child)))
(iter (for added-child in added-children)
(qconc intervals-to-add (add-slot-to-intervals (intervals-of-node added-child) slot)))))
(t ;; was (and (not (listp old)) (not (listp new)))
(qpreconc (intervals-of-node old) intervals-to-remove)
(qpreconc (add-slot-to-intervals (intervals-of-node new) slot) intervals-to-add)))))
(flet ((record-node (e)
(setf (ft/it:node e) new-node)))
(declare (dynamic-extent #'record-node))
(handler-bind ((ft/it:interval-collision-error #'record-node))
(setf (slot-value new-node 'descendant-map)
(ft/it:itree-add-intervals
(ft/it:itree-remove-intervals old-dm
(qlist intervals-to-remove))
(qlist intervals-to-add))))))
new-node))
;;; TODO -- specialize this in define-node-class
(defmethod tree-copy ((node node))
(let* ((child-slots (slot-value node 'child-slots))
(slots (remove-if (lambda (slot) (eql :class (slot-definition-allocation slot)))
(class-slots (class-of node))))
(slot-names (remove-if (lambda (s) (or (eql s 'serial-number)
(eql s 'descendant-map)))
(cl:mapcar #'slot-definition-name slots)))
(initializers (mappend (lambda (slot)
(and (slot-boundp node slot)
(list (make-keyword slot)
(slot-value node slot))))
slot-names))
(new-node (apply #'make-instance (class-of node)
initializers)))
;; Now write over the child slots
;; This is ok, as the descendant-map slot is uninitialized
(iter (for c in child-slots)
(if (consp c)
(destructuring-bind (child-slot-name . arity) c
(if (eql arity 1)
;; Special case: a singleton child
(setf (slot-value new-node child-slot-name)
(tree-copy (slot-value new-node child-slot-name)))
(setf (slot-value new-node child-slot-name)
(cl:mapcar #'tree-copy (slot-value new-node child-slot-name)))))
(setf (slot-value new-node c)
(cl:mapcar #'tree-copy (slot-value new-node c)))))
new-node))
(defun childs-list (node slot)
(let ((val (slot-value node slot)))
(if (listp val) val (list val))))
(defun child-slot-with-sn (node sn)
(when-let ((itree-node (ft/it::itree-find-node-splay (descendant-map node) sn)))
(ft/it:node-data itree-node)))
(defgeneric rpath-to-node (root node &key error)
(:documentation "Returns the (reversed) path from ROOT to a node
with the same serial number as NODE, as a list of nodes. Note that this does
not include NODE itself.
Also return the node found. If no such node is in the tree, return NIL NIL, or
signal an error if ERROR is true.")
(:method ((root node) (node node) &key error)
(rpath-to-node root (serial-number node) :error error))
(:method ((root node) (sn integer) &key error)
(unless (eql (serial-number root) sn)
(let ((node root)
(rpath nil)
(child-slot (child-slot-with-sn root sn)))
(iter (while node)
(unless child-slot
(if error
(error "Serial number ~a not found in tree ~a" sn root)
(return (values nil nil))))
(push node rpath)
(iter (for child-node in (childs-list node child-slot))
(when (typep child-node 'node)
(when (eql (serial-number child-node) sn)
(return-from rpath-to-node (values rpath child-node)))
(let ((grandchild-slot (child-slot-with-sn child-node sn)))
(when grandchild-slot
(setf child-slot grandchild-slot
node child-node)
(return))))
(finally
;; This should never happen if the tree is well formed
(error "Could not find child with sn ~a in slot ~a"
sn child-slot))))))))
(defgeneric path-of-node (root node &key error)
(:documentation "Return the path from ROOT to NODE, in a form
suitable for use by @ or LOOKUP. If the node is not in the tree
return NIL, unless ERROR is true, in which case error.")
(:method ((root node) (node node) &key (error nil))
(path-of-node root (serial-number node) :error error))
(:method ((root node) (serial-number integer) &key (error nil))
(multiple-value-bind (rpath found) (rpath-to-node root serial-number)
(if found
;; Translate the rpath to actual path
(let ((child found)
(path nil))
(iter (for a in rpath)
(let ((slot (when-let ((itree-node (ft/it::itree-find-node-splay
(descendant-map a)
(serial-number child)
)))
(ft/it:node-data itree-node))))
(assert slot () "Could not find SLOT of ~a in descendant map of ~a" child a)
(let ((v (slot-value a slot)))
(push
(if (listp v)
(let ((pos (position child v)))
(assert pos () "Could not find ~a in slot ~a of ~a" child slot a)
(cons slot pos))
(progn
(assert (eq v child) () "Child ~a is not the value of slot ~a of ~a" child slot a)
slot))
path)))
(setf child a))
path)
(if error (error "Could not find ~a in ~a" serial-number root) nil)))))
(defgeneric parent (root node)
(:documentation "Return the parent of NODE.
Return nil if NODE is equal to ROOT or is not in the subtree of ROOT.")
(:method ((root node) (node node))
(car (rpath-to-node root node))))
(defgeneric predecessor (root node)
(:documentation "Return the predecessor of NODE with respect to ROOT if one exists.")
(:method ((root node) (node node))
(when-let (parent (parent root node))
(iter (for child in (children parent))
(for prev previous child)
(when (eq child node)
(return prev))))))
(defgeneric successor (root node)
(:documentation "Return the successor of NODE with respect to ROOT if one exists.")
(:method ((root node) (node node))
(when-let (parent (parent root node))
(second (member node (children parent))))))
(defun child-list (node slot-spec)
(let ((children (slot-value node (slot-spec-slot slot-spec))))
(if (eql 1 (slot-spec-arity slot-spec))
(list children)
children)))
(defmacro do-tree ((var tree
&key
;; (start nil startp) (end nil endp)
;; (from-end nil from-end-p)
(index nil indexp) (rebuild)
(value nil valuep))
&body body)
"Generalized tree traversal used to implement common lisp sequence functions.
VALUE is the value to return upon completion. INDEX may hold a
variable bound in BODY to the *reversed* path leading to the current
node. If REBUILD then the body should return the new node that will
replace NODE, NODE itself if it is not to be replaced, and NIL if NODE
is to be deleted (from a variable arity list of children in its parent)."
;; (declare (ignorable start end from-end))
;; (when (or startp endp from-end-p)
;; (warn "TODO: implement start end and from-end-p."))
(when (and rebuild indexp)
(error "Does not support :index with :rebuild"))
(with-gensyms (block-name body-fn tree-var)
`(progn
(nest
(block ,block-name)
(flet ((,body-fn (,var ,@(when indexp (list index)))
,@(if rebuild
body
`((multiple-value-bind (exit result)
(let () ,@body)
(when exit (return-from ,block-name
(values exit result))))
nil))))
(declare (dynamic-extent #',body-fn)))
(let ((,tree-var ,tree)))
,(cond
;; (rebuild `(update-predecessor-tree ,tree-var (traverse-tree ,tree-var #',body-fn)))
(rebuild `(compute-descendant-map ,tree-var (traverse-tree ,tree-var #',body-fn)))
(indexp `(pure-traverse-tree/i ,tree-var nil #',body-fn))
(t `(pure-traverse-tree ,tree-var #',body-fn))))
,@(when valuep (list value)))))
(defgeneric pure-traverse-tree/i (node index fn)
(:documentation "Traverse tree below NODE in preorder, calling
FN on each node (and with the reversed path INDEX to that node)."))
(defmethod pure-traverse-tree/i ((node t) (index list) (fn function)) nil)
(defmethod pure-traverse-tree/i ((node node) (index list) (fn function))
(funcall fn node index)
(map-children/i node index fn))
(defgeneric pure-traverse-tree (node fn)
(:documentation "Traverse tree at and below NODE in preorder,
calling FN on each node."))
(defmethod pure-traverse-tree ((node t) (fn function)) nil)
(defmethod pure-traverse-tree ((node node) (fn function))
(funcall fn node)
(map-children node fn))
(defgeneric traverse-tree (node fn)
(:documentation "Traverse tree rooted at NODE in preorder. At each
node, call FN. If the returned value is non-nil, it replaces the node
and traversal continues. If the returned value is nil stop traversal.
If any child is replaced also replace the parent node (as the trees
are applicative.)"))
(defmethod traverse-tree ((node t) (fn function)) node)
(defmethod traverse-tree ((node node) (fn function))
(block nil
(let ((new (funcall fn node)))
(when (null new) (return nil))
(if-let ((keys (mapcar-children new fn)))
(apply #'copy new keys)
new))))
(defgeneric map-only-children/i (node index fn)
(:documentation "Call FN on each child of NODE, along with
the INDEX augmented by the label of that child. Do not descend
into subtrees."))
(defgeneric map-children/i (node index fn)
(:documentation "Call FN on each child of NODE, along with the INDEX
augmented by the label of that child, and descrend into subtrees in
depth first order"))
(defmacro def-map-children/i (name child-op)
"Define a method for a map-children-like method. There was much
code duplication here before."
;; TODO: change this to work with slot-specifier objects
`(defmethod ,name ((node node) (index list) (fn function))
(let* ((child-slots (child-slots node)))
(declare (type fixnum))
(dolist (child-slot child-slots)
(let ((name (slot-spec-slot child-slot)))
(if (eql 1 (slot-spec-arity child-slot))
;; Single arity just add slot name.
(,child-op (slot-value node name)
;; TODO: precompute this keyword in slot-spec
(list* name index)
fn)
;; Otherwise add slot name and index into slot.
(let ((child-list (child-list node child-slot))
(counter 0))
(declare (type fixnum counter))
(dolist (child child-list)
(,child-op
child (list* (cons name counter) index) fn)
(incf counter)))))))))
(def-map-children/i map-children/i pure-traverse-tree/i)
(def-map-children/i map-only-children/i (lambda (child path fn) (funcall fn child path)))