-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspecops.lisp
More file actions
2175 lines (1975 loc) · 122 KB
/
Copy pathspecops.lisp
File metadata and controls
2175 lines (1975 loc) · 122 KB
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
;;;; specops.lisp
(in-package #:specops)
(defun find-width (number unit)
"Return the number of UNIT-bit units needed to represent NUMBER. Non-negative
values are sized by magnitude; negative values are sized for their two's-complement
representation, including the sign bit. Zero has width 0."
(if (zerop number)
0 (ceiling (if (minusp number)
(1+ (integer-length number))
(integer-length number))
unit)))
(defun serialize (item unit collector)
"Serialize a series of integers, integer vectors and/or serial integer specifications into a vector of integers of a given width. A serial integer specification takes the form of a pair of a value and the number of elements it is intended to serialize to."
(let ((mask (1- (ash 1 unit)))) ;; TODO: find a way to create the mask just once?
(flet ((decompose (number starting-width)
(let ((shift (- (* unit (1- starting-width)))))
(loop :for i :below starting-width
:do (funcall collector (logand mask (ash number shift)))
(incf shift unit)))))
(if (integerp item) ;; values that fit within a byte are just pushed on
(if (zerop (ash item (- unit)))
(funcall collector item)
(decompose item (find-width item unit)))
(if (and (consp item) (not (listp (rest item))))
;; handle cons cells encoding width and value, like (3 . 5) → #x000005
(destructuring-bind (width &rest value) item
(decompose value width))
(if (vectorp item)
(loop :for i :across item :do (funcall collector i))
(error "Attempted to serialize incompatible value - must be an integer, a vector or a pair indicating integer value and encoding width.")))))))
;; (defun serialize (item unit collector &optional (swap-granularity 0))
;; "Serialize a series of integers, integer vectors and/or serial integer specifications into a vector of integers of a given width. A serial integer specification takes the form of a pair of a value and the number of elements it is intended to serialize to."
;; (when (zerop unit)
;; (error "Unit cannot be zero."))
;; (let ((mask (1- (ash 1 unit))) ;; TODO: find a way to create the mask just once?
;; (increment (* unit (if (zerop swap-granularity) 1 -1)))
;; (shift-factor (if (zerop swap-granularity) -1 0))
;; (vshift (let ((u unit))
;; (loop :for i :from 1 :do (setf u (ash u -1)) :when (= 1 (logand 1 u)) :return i))))
;; (flet ((decompose (number starting-width)
;; (let ((shift (* shift-factor (ash (1- starting-width) vshift))))
;; (loop :for i :below starting-width
;; :do (funcall collector (logand mask (ash number shift)))
;; (incf shift increment)))))
;; (if (integerp item) ;; values that fit within a byte are just pushed on
;; (if (zerop (ash item (- unit)))
;; (funcall collector item)
;; (decompose item (find-width item unit)))
;; (if (and (consp item) (not (listp (rest item))))
;; ;; handle cons cells encoding width and value, like (3 . 5) → #x000005
;; (destructuring-bind (width &rest value) item
;; (decompose value width))
;; (if (vectorp item)
;; (let* ((type (array-element-type item))
;; ;; number of units to decompose; not needed if the vector's element width
;; ;; is the same as the unit width to serialize
;; (el-width (and (listp type) (eql 'unsigned-byte (first type))
;; (second type)))
;; (dc-width (if (= el-width unit)
;; 0 (ash el-width (- vshift)))))
;; (loop :for i :across item :do (if (zerop dc-width) (funcall collector i)
;; (decompose i dc-width))))
;; (error "Attempted to serialize incompatible value - must be an integer, a vector or a pair indicating integer value and encoding width.")))))))
(defun swap-segments (value width granularity)
"Swap segments of a number for cross-endian encoding. This function supports
swapping at multiple levels of granularity to support systems like the PDP-11,
where words are entered in little-endian order with big-endian byte order
within words."
(if (zerop granularity)
value (let* ((span (ash 1 (+ 2 granularity)))
(mask (1- (ash 1 span)))
(shift 0) (output 0) (count (ash width (- (1- granularity)))))
(dotimes (i count)
(incf output (logand mask (ash value shift)))
(unless (= i (1- count))
(setf output (ash output span)))
(decf shift span))
output)))
(defun serializer-for (&optional (unit-power 0) (swap-by 0))
"Serialize a series of integers, integer vectors and/or serial integer specifications
into a vector of integers of a given width. A serial integer specification takes the
form of a pair of a value and the number of elements it is intended to serialize to. This
function can output at multiple unit widths, as determined by the unit-power argument
expressing the (power+3) of 2 corresponding to the width at which output will be generated."
(let* ((unit (ash 1 (+ 3 unit-power)))
(mask (1- (ash 1 unit))))
(flet ((decompose (collector value starting-width)
(let ((shift (- (- (* unit starting-width) unit))))
(loop :repeat starting-width
:do (funcall collector (logand mask (ash value shift)))
(incf shift unit)))))
(lambda (item collector)
(typecase item
(integer (if (zerop (ash item (- unit)))
;; values that fit within a unit are sent directly
(funcall collector (swap-segments item (ash 1 unit-power) swap-by))
(let ((width (find-width item unit)))
(decompose collector (swap-segments item (ash width unit-power) swap-by)
width))))
(cons (if (null (rest item)) ;; nil cdr values cause zero-padding
(loop :repeat (first item) :do (funcall collector 0))
(if (listp (rest item))
(error "Incompatible cons entry.")
;; handle cons cells encoding width and value, like (3 . 5) → #x000005
(destructuring-bind (width &rest value) item
(when (> (find-width value unit) width)
(error "Value ~a does not fit within ~a unit(s) of ~a bits." value width unit))
(decompose collector (swap-segments value (ash width unit-power) swap-by)
width)))))
(vector (let* ((type (array-element-type item))
(el-width (and (listp type) (eql 'unsigned-byte (first type))
(second type)))
(dc-width (if (= el-width unit)
0 (ash el-width (- (+ 3 unit-power))))))
;; (print (list :ty unit el-width dc-width))
(loop :for i :across item
:do (if (zerop dc-width) (funcall collector i)
(decompose collector
(swap-segments i (ash dc-width unit-power) swap-by)
dc-width)))))
(t (error "Attempted to serialize incompatible value - must be an integer, a vector or a pair indicating integer value and encoding width.")))))))
;; (defun make-array-writer (array &key num-width)
;; (lambda (offset &rest numbers)
;; (let ((width) (mask) (count 0) (eltype (array-element-type array)))
;; (if (and (listp eltype) (eql 'unsigned-byte (first eltype))
;; (member (second eltype) '(8 16 32 64)))
;; (setf width (second eltype)
;; mask (1- (ash 1 width)))
;; (error "Invalid collection array; only unsigned arrays of 8, 16, 32 or 64-bit integers may be used."))
;; (loop :for number :in numbers
;; :do (let ((num-width (or num-width (find-width number width)))
;; (base count))
;; (loop :for n :below num-width
;; :do (setf (row-major-aref array (+ offset base (- num-width 1 n)))
;; (logand mask number))
;; (setf number (ash number (- width)))
;; (incf count))))
;; count)))
;; (defun serialize (item unit collector)
;; (let ((mask (1- (ash 1 unit)))) ;; TODO: find a way to create the mask just once?
;; (flet ((decompose (number starting-width)
;; (print (list :sw starting-width unit))
;; (let ((shift (- (* unit starting-width))))
;; (loop :for i :below starting-width
;; :do (funcall collector (logand mask (ash number shift)))
;; (incf shift unit)))))
;; (print (list :it item))
;; (if (integerp item) ;; values that fit within a byte are just pushed on
;; (if (zerop (ash item (- unit)))
;; (funcall collector item)
;; (decompose item (1- (find-width item unit))))
;; (if (and (consp item) (not (listp (rest item))))
;; ;; handle cons cells encoding width and value, like (3 . 5) → #x000005
;; (destructuring-bind (width &rest value) item
;; (decompose value (1- width)))
;; (if (vectorp item)
;; (loop :for i :across item :do (funcall collector i))
;; (error "Attempted to serialize incompatible value - must be an integer, a vector or a pair indicating integer value and encoding width.")))))))
(defun join-spec (unit items)
(let ((shift (- unit)) (mask (1- (ash 1 unit))))
(let ((collected))
(loop :for item :in items :when item ;; ignore null items
:do (if (numberp item) ;; values that fit within a byte are just pushed on
(if (zerop (ash item shift))
(push item collected)
(let ((sub-collected))
(loop :until (zerop item)
:do (push (logand item mask) sub-collected)
(setf item (ash item shift)))
(setf collected (append (reverse sub-collected) collected))))
(if (and (consp item) (not (listp (rest item))))
;; handle cons cells encoding width and value, like (3 . 5) → #x000005
(destructuring-bind (width &rest value) item
(let ((sub-collected))
(loop :for i :below width :do (push (logand value mask) sub-collected)
(setf value (ash value shift)))
(setf collected (append (reverse sub-collected) collected))))
(when (vectorp item)
(loop :for i :across item :do (push i collected))))))
(make-array (length collected) :element-type (list 'unsigned-byte unit)
:initial-contents (reverse collected)))))
(defun joinb (&rest items)
(join-spec 8 items))
(defun joinw (&rest items)
(join-spec 16 items))
(defun flipbits (b &optional (n 32))
(let ((r 0))
(dotimes (x n r)
(setq r (logior (ash r 1) (logand b 1))
b (ash b -1)))))
(defmacro defcodetable (symbol options &rest rows)
(let ((assignments)
(blank-symbol (caar rows))
(table (gensym)) (xtable (gensym)) (char (gensym))
(store (rest (assoc :store options))))
(dolist (row (rest rows))
(let ((base (first row)))
(loop :for ix :from 1 :for item :in (rest row) :for increment :in (cdar rows)
:do (typecase item
(symbol)
(character
(push (+ base increment) assignments)
(push (case store
(:htable `(gethash (char-code ,item) ,table))
(:vector `(aref ,table (char-code ,item))))
assignments))))))
`(let ((,table ,(case store
(:vector `(make-array 256 :initial-element #x00 :element-type '(unsigned-byte 8)))
(:htable `(make-hash-table))))
(,xtable (make-array 256 :element-type 'character)))
(setf ,@assignments)
,(case store
(:vector `(loop :for x :across ,table :for ix :from 0 :do (setf (aref ,xtable x) (code-char ix))))
(:htable `(loop :for x :being :the :hash-keys :of ,table :for ix :from 0
:do (when t ; (gethash x ,table)
;; (print (list :aa x))
(setf (aref ,xtable (gethash x ,table)) (code-char x))))))
(setf (symbol-function ',symbol)
(lambda (,char)
(typecase ,char
(character ,(case store
(:vector `(aref ,table (char-code ,char)))
(:htable `(gethash (char-code ,char) ,table))))
(integer (aref ,xtable ,char))))))))
(defun quantify-mask-string (string params)
(let ((segments) (symbols) (factor) (base 0) (bits 0) (width 1) (sx 0) (enumask "01"))
(when (and (< 1 (length string)) (char= #\: (aref string 1)))
(incf sx 2) ;; skip reading the type prefix
;; bodh for binary, octal, decimal, hexadecimal;
;; b is the default case so it's unhandled here
(case (position (char-upcase (aref string 0)) "BODH" :test #'char=)
(1 (setf width 3
enumask "01234567"))
(2 (setf factor 10 ;; decimal uses the factor multiplication mode
enumask "0123456789"))
;; for hexadecimal, uppercase A-F register as digits while lowercase represent symbols
(3 (setf width 4
enumask "0123456789ABCDEF"))))
(loop :repeat (- (length string) sx)
:do (let ((char (aref string sx)))
(if (char= #\. char)
(incf sx) ;; period is an ignored spacing character
(let ((index (position char enumask :test #'char=)))
(if index (progn (when (and symbols (not (null (first symbols))))
(push nil symbols)
(push bits segments))
(incf base index))
(when (or (not symbols) (not (eq (intern (string-upcase char) "KEYWORD")
(first symbols))))
(push (intern (string-upcase char) "KEYWORD") symbols)
(push bits segments)))
(unless (= sx (1- (length string)))
(setf base (if factor (* base factor)
(ash base width))))
;; (print (list :bt bits ))
(incf bits width)
(incf sx)))))
;; (print (list :ss segments))
(let ((segments (if factor (cons 1 (reverse (loop :for s :in segments :collect (expt factor (1- s)))))
(cons 0 (loop :for s :in segments :collect (abs (- s bits)))))))
;; (print (list :seg segments symbols bits))
(values (loop :for pair :in (rest (assoc :static params)) ;; values
:do (destructuring-bind (sym value) pair
(let* ((insym (intern (string-upcase sym) "KEYWORD"))
(index (loop :for s :in symbols :for ix :from 0
:when (eq s insym) :return ix)))
;; (when reverse-match (push insym static-segments))
(if index (incf base (ash value (nth index segments)))
(error "Invalid key for static base value increment."))))
:finally (return base))
;; (cons 0 (loop :for s :in segments :collect (abs (- s bits))))
segments symbols bits))))
;; (defun quantify-mask-string2 (string params)
;; (let ((segments) (symbols) (base 0) (bits 0))
;; (if (char= #\# (aref string 0)) ;; initial # means the string is hexadecimal
;; (loop :for c :across string :for ix :from 0 :when (not (or (zerop ix)
;; (char= c #\.)))
;; :do (let ((index (position c "0123456789ABCDEF" :test #'char=)))
;; ;; symbol-denoting characters must be lowercase when entering hexadecimal strings
;; (if index
;; (progn (when (and symbols (not (null (first symbols))))
;; (push nil symbols)
;; (push bits segments))
;; (incf base index))
;; (when (or (not symbols) (not (eq (intern (string-upcase c) "KEYWORD")
;; (first symbols))))
;; (push (intern (string-upcase c) "KEYWORD") symbols)
;; (push bits segments)))
;; (unless (= ix (1- (length string))) (setf base (ash base 4)))
;; (incf bits 4)))
;; (loop :for c :across string :for ix :from 0 :when (not (char= c #\.)) ;; period is used as a spacer
;; :do (if (position c "01" :test #'char=)
;; (progn (when (and symbols (not (null (first symbols))))
;; (push nil symbols)
;; (push bits segments))
;; (when (char= c #\1) (incf base))) ;; set constant 1 bits
;; (when (or (not symbols) (not (eq (intern (string-upcase c) "KEYWORD")
;; (first symbols))))
;; (push (intern (string-upcase c) "KEYWORD") symbols)
;; (push bits segments)))
;; ;; shift the number to the left unless this is the last digit
;; (unless (= ix (1- (length string))) (setf base (ash base 1)))
;; (incf bits)))
;; (let ((segments (cons 0 (loop :for s :in segments :collect (abs (- s bits))))))
;; ;; (print (list :seg segments symbols bits))
;; (values (loop :for pair :in (rest (assoc :static params)) ;; values
;; :do (destructuring-bind (sym value) pair
;; (let* ((insym (intern (string-upcase sym) "KEYWORD"))
;; (index (loop :for s :in symbols :for ix :from 0
;; :when (eq s insym) :return ix)))
;; ;; (when reverse-match (push insym static-segments))
;; (if index (incf base (ash value (nth index segments)))
;; (error "Invalid key for static base value increment."))))
;; :finally (return base))
;; ;; (cons 0 (loop :for s :in segments :collect (abs (- s bits))))
;; segments symbols bits))))
(defmacro masque (string &rest assignments)
(let* ((base-sym (gensym))
(params (if (listp (caar assignments)) (first assignments) nil))
(assignments (if (not params) assignments (rest assignments)))
(processor (rest (assoc :with-processor params))))
(multiple-value-bind (base segments symbols) (quantify-mask-string string params)
;; (print (list :ss segments symbols params))
;; (format t "~v,'0B~%" 16 (ash (1- (ash 1 length)) (nth index segments)))
;; (print segments)
(if processor
(let* ((rev-sym (reverse symbols)) (rev-seg (reverse segments))
(big-endian (eq :big (rest (assoc :endian params))))
(width (rest (assoc :width params))) (mask (1- (ash 1 width))))
(cons 'progn
(loop :for assignment :in assignments :for sym :in rev-sym
:for seg :in rev-seg :for n :from 0
:append (destructuring-bind (key value) assignment
(let ((index (position (intern (string-upcase key) "KEYWORD")
symbols))
(seg-length (if (= n (1- (length assignments)))
(nth n rev-seg)
(- (nth n rev-seg) (nth (1+ n) rev-seg)))))
(when (not index)
(error "Symbol ~a not found in mask ~a." key string))
(let ((divs (/ seg-length width)))
;; (print (list :ee divs length))
(if (= 1 divs)
`((funcall ,processor ,value))
(loop :for d :below divs
:collect `(funcall ,processor
(logand (ash ,value
,(- (* 8 (if big-endian
d (- divs 1 d)))))
,mask))))))))))
(let* ((irregular (= 1 (first segments)))
(steps (loop :for assignment :in assignments
:collect (destructuring-bind (key value) assignment
(let ((index (position (intern (string-upcase key) "KEYWORD")
symbols)))
(when (not index)
(error "Symbol ~a not found in mask ~a." key string))
(let ((length (- (nth (1+ index) segments) (nth index segments))))
(if irregular `(incf ,base-sym (* ,value ,(nth index segments)))
`(setf ,base-sym
(logior ,base-sym
(ash (logand ,value ,(1- (ash 1 length)))
,(nth index segments)))))
))))))
(if (not steps)
base `(let ((,base-sym ,base)) ,@steps ,base-sym)))))))
(defmacro unmasque (string test-value params-or-keys &body body)
(let* ((params (if (listp (first params-or-keys)) params-or-keys nil))
(keys (if (not params) params-or-keys (first body)))
(body (if (not params) body (rest body))))
(multiple-value-bind (base segments symbols bits) (quantify-mask-string string params)
(let* ((variant-mask (1- (ash 1 bits)))
(pairs (loop :for key :in keys
:collect (let* ((index (position (intern (string-upcase key) "KEYWORD")
symbols))
(length (- (nth (1+ index) segments) (nth index segments))))
(decf variant-mask (ash (1- (ash 1 length)) (nth index segments)))
`(,key (logand ,(1- (ash 1 length))
(ash ,test-value ,(- (nth index segments)))))))))
;; (print (list :vm (format nil "~v,'0B" 16 variant-mask)
;; (format nil "~v,'0B" 16 base)))
`(if (/= ,base (logand ,variant-mask ,test-value))
nil (let ,pairs ,@body))))))
(defun txcodec-ebcdic (a) (print a))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *manifests* (make-hash-table :test 'eq))
(defvar *enums* (make-hash-table :test 'eq)))
(defmacro defenum (name params &body map)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (gethash ',name *enums*)
,(append (list 'list (cons 'list params))
map))))
;; ===============================================================
;; LEB128 encoding utilities
;; ===============================================================
(defun encode-leb128-unsigned (value writer)
"Encode a non-negative integer as an unsigned LEB128 byte vector."
(declare (type (integer 0) value))
(if (zerop value)
(funcall writer 0)
(loop :while (plusp value)
:do (let ((byte (logand value #x7F)))
(setf value (ash value -7))
(when (plusp value)
(setf byte (logior byte #x80)))
(funcall writer byte)))))
(defun encode-leb128-signed (value writer)
"Encode an integer as a signed LEB128 byte vector."
(let ((more t))
(loop :while more
:do (let ((byte (logand value #x7F)))
(setf value (ash value -7))
(if (or (and (zerop value) (zerop (logand byte #x40)))
(and (= value -1) (not (zerop (logand byte #x40)))))
(setf more nil)
(setf byte (logior byte #x80)))
(funcall writer byte)))))
(defmacro defmanifest (name params &body fields)
(destructuring-bind (&key unit endian index vextend-by count-from length pad offset) params
(let* ((unit-spec (typecase unit
(integer (if (< unit 4)
;; the unit may be an exponent of 2 + 3
unit (multiple-value-bind (root remainder) (floor (log unit 2))
(if (zerop remainder) (- root 3)
(error "Invalid unit.")))))
(symbol (case unit (:byte 0) (:word 1) (:doubleword 2) (:quadword 3)))))
(swap-by (case endian (:big 0) (:little 1) (:middle 2) (:pdp 2)))
(field-specs (list (list 'list :type :config :unit-spec unit-spec
:pad pad :length length)))
(index 0))
(labels ((format-slot-spec (spec)
;; quote functions mentioned in slot specs for proper marshal macroexpansion
(cons 'list (loop :for item :in spec
:collect (if (not (and (listp item) (eql 'function (first item))))
item (list 'quote item)))))
(process-field (field-spec &optional unincrementing)
(destructuring-bind (symbol predicate &key (endian 0) length enumerate-by end-by
count default slot &allow-other-keys)
field-spec
(let ((width) (signed) (subtype-list) (type-indicator) (type-conditions)
(this-swap-by (case endian
(:big 0) (:little 1) (:middle 2) (:pdp 2)
(t endian))))
;; (when slot (setf (getf (cdar field-specs) :has-slots) t))
(typecase predicate
(null (setf width 1))
(keyword (if (zerop unit-spec)
(case predicate
(:u8 (setf width 1 signed nil))
(:s8 (setf width 1 signed t))
(:u16 (setf width 2 signed nil))
(:s16 (setf width 2 signed t))
(:u32 (setf width 4 signed nil))
(:s32 (setf width 4 signed t))
(:u64 (setf width 8 signed nil))
(:s64 (setf width 8 signed t))
(:str (setf width 1)))
(error "Type symbols are only valid for 8-bit output.")))
(list (destructuring-bind (is-signed count &rest subtypes) predicate
(print (list :cc is-signed))
(if (eq :case is-signed)
(setf type-indicator count
type-conditions
(cons 'list (mapcar (lambda (i) (cons 'list i)) subtypes))
width 1) ;; how to handle right?
(setf width count
subtype-list subtypes))
;; (print (list :sty subtypes))
(when (eq :s is-signed) (setf signed t)))))
(unless unincrementing (incf index (ash width (- unit-spec))))
(list 'list
:name (and (not (string= "_" (symbol-name symbol))) symbol)
:signed signed :length (ash width (- unit-spec))
:count count :enumerate-by (list 'quote enumerate-by)
:slot (format-slot-spec slot)
:type-indicator type-indicator :type-conditions type-conditions
:subtypes (and subtype-list (cons 'list subtype-list))
:end-by end-by :swap-by (or this-swap-by swap-by)
:default default))))
(process-entry (f accumulator)
(typecase (first f)
(keyword (push (process-field f) accumulator))
(symbol (case (first f)
(span (let ((sub-items))
(dolist (item (cddr f))
;; cons the name of the closure to the context list
(setf sub-items (process-entry item sub-items)))
(push (list 'list :type :span :name (second f)
:items (cons 'list (reverse sub-items)))
accumulator)))
(pad (destructuring-bind (with for-or-spec &optional spec-arg) (rest f)
(let ((count (if (integerp for-or-spec)
for-or-spec (case for-or-spec
(:to (- spec-arg index))
;; the align argument lets you align
;; output to a given byte granularity
(:align (mod index spec-arg))))))
(incf index count)
(push (list 'list :type :pad :with with :length count
:upto (and (eq :to for-or-spec) spec-arg)
:swap-by swap-by)
;; might need it for nonzero padding
accumulator))))
(str (destructuring-bind (actual &key encode-by length terminated-by) (rest f)
(let ((count (* (length actual) (or length 1))))
(push (list 'list :type :string :actual actual :swap-by swap-by
:terminated-by terminated-by :length count
:encode-by (list 'quote encode-by))
accumulator)
(incf index count))))
(masque (destructuring-bind (spec-string &rest bindings) (rest f)
(let ((bindings-out))
(dolist (b bindings)
(push (if (keywordp (second b))
(let ((field-out (process-field (rest b) t)))
(setf (getf (rest field-out) :bind-to)
(list 'quote (first b)))
field-out)
(list 'list :binding (list 'quote b)))
bindings-out))
(let* ((masque-width (nth-value 3 (quantify-mask-string
spec-string nil)))
(unit-width
(+ (ash masque-width (- (+ 3 unit-spec)))
(if (zerop (logand masque-width
(1- (ash 1 (+ 3 unit-spec)))))
0 1))))
;; increment the index from the actual masque field width;
;; in the case of an unaligned masque field the output gets
;; padded, but this would be a mistake, in pracice masques
;; should always line up with the output unit
(incf index unit-width)
(push (list 'list :type :masque :length unit-width
:actual spec-string :swap-by swap-by
:bindings (cons 'list (reverse bindings-out)))
accumulator)))))
(manifest (push (list 'list :type :manifest :name (second f)
:actual (list 'quote (cddr f)))
accumulator))))
(t (error "Invalid clause; may not start with ~a." (first f))))
accumulator))
(dolist (f fields) (setf field-specs (process-entry f field-specs)))
(when (and length (< index length))
(push (list 'list :type :pad :with (or pad 0) :offset offset
:swap-by swap-by :length (- length index))
field-specs))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (gethash ',name *manifests*)
,(cons 'list (reverse field-specs))))))))
(defun cs-adapt (item)
(if (and (vectorp item)
(typep item '(unsigned-byte 8)))
item (if (vectorp item)
(let ((output (make-array (length item) :element-type '(unsigned-byte 8))))
(loop :for i :across item :for ix :from 0 :do (setf (aref output ix) i))
output))))
(defun find-in-manifest (spec handler)
(let ((output))
(loop :for item :in spec :until output
:do (setf output (if (eq :span (getf item :type))
(find-in-manifest (getf item :items) handler)
(funcall handler item))))
output))
(defmacro marshal (name destination &body pairs)
(let* ((spec (gethash name *manifests*))
(params (first spec))
(regions) (slots) (slots-of)
(swap-specs) (offset)
(access) (enter) (index) (tell) (write) (prefix)
(values) (length) (serializers) (map) (b) (i)
;; (access (gensym "AC")) (enter (gensym "EN")) (index (gensym "IN"))
;; (tell (gensym "TL")) (write (gensym "WR")) (bindings-sym (gensym "BN"))
;; (values (gensym "VL")) (length (gensym "LN")) (serializers (gensym "SR"))
;; (map (gensym "MP")) (b (gensym "BB")) (i (gensym "II"))
(olength) (sub-lexicon))
;; populate the symbol lexicon or import it from an enclosing marshal macro
(if (getf pairs :-+sub-lexicon+-)
(destructuring-bind (&key ac-sym en-sym in-sym tl-sym wr-sym pr-sym
vl-sym ln-sym sr-sym mp-sym b-sym i-sym)
(getf pairs :-+sub-lexicon+-)
(setf access ac-sym enter en-sym index in-sym tell tl-sym write wr-sym prefix pr-sym
values vl-sym length ln-sym serializers sr-sym map mp-sym b b-sym i i-sym
;; propagate the same lexicon to deeper sub-manifests so nested
;; inlining keeps sharing the top-level environment
sub-lexicon (getf pairs :-+sub-lexicon+-)))
(setf access (gensym "AC")
enter (gensym "EN")
index (gensym "IN")
tell (gensym "TL")
write (gensym "WR")
;; bindings-sym (gensym "BN")
values (gensym "VL")
length (gensym "LN")
serializers (gensym "SR")
map (gensym "MP")
b (gensym "BB")
i (gensym "II")
sub-lexicon (list :ac-sym access :en-sym enter :in-sym index :tl-sym tell
:wr-sym write ;; :bn-sym bindings-sym
:vl-sym values :ln-sym length
:sr-sym serializers :mp-sym map :b-sym b :i-sym i)))
(setf olength length)
(setf swap-specs (remove-duplicates swap-specs))
(labels ((preprocess-spec (spec-items)
(dolist (item spec-items)
(destructuring-bind (&key length name swap-by type slot items &allow-other-keys) item
;; build list of swap specs for endian conversion
(when swap-by (push swap-by swap-specs))
(setf offset (getf item :offset))
;; strings always use the 0-mode swap because they use no endian conversion;
;; endian handling is done within the string codec if necessary
;; since there are many string formats with different endian properties
(push (qualify name) regions)
(when slot
(push item slots)
(push (list (qualify name) (first slot) length swap-by)
(getf slots-of (qualify (second slot)))))
(case type
(:span (preprocess-spec items)))
(when (eq type :string) (push 0 swap-specs)))))
(qualify (name)
(if (not (and prefix name))
name (intern (format nil "~a/~a" prefix name) :keyword)))
(resolve-region (name slot-field slot-type slot-width swap-by)
`(funcall ,write (aref ,serializers ,swap-by)
(cons ,slot-width
;; :length-of → (- end start) ; :offset-of → start
,(case slot-type
(:length-of `(- (third (assoc ,name ,map))
(second (assoc ,name ,map))))
(:offset-of `(second (assoc ,name ,map)))))
(second (assoc ',slot-field ,map)))) ; slot's reserved position
(assign-serializer (s)
`(setf (aref ,serializers ,s)
(serializer-for ,(getf params :unit-spec) ,s)))
(masque-binder (b)
(if (eq :binding (first b))
(second b)
(destructuring-bind (&key bind-to &allow-other-keys) b
(list (getf b :bind-to) (or (getf pairs (getf b :name)) 0)))))
(enumerate (table-name value)
(if (not table-name)
value (let ((table (gethash table-name *enums*)))
(typecase value
(keyword (getf (rest table) value))))))
(generate (item &optional context)
(destructuring-bind (&key name type kind signed (swap-by 0) upto default offset
count actual bindings with length encode-by end-by
type-indicator type-conditions
slot enumerate-by subtypes items)
item
(let ((qname (qualify name)))
;; (when context (setf name (intern (format nil "~a/~a" (first context) name)
;; "KEYWORD")))
;; (print (list :nn name context))
;; types: ; :scalar | :pad | :masque | :bytes | :sized | :leb | :name | :slot
(case type
(:pad `(:-pad
(loop :repeat ,(if (not upto) length `(max 0 (- ,upto ,index)))
:do (funcall (aref ,serializers ,swap-by) ,with ,enter))
(assert (<= ,index ,olength) ()
"Out of bounds.")))
(:string `(,name
(funcall (aref ,serializers 0)
;; strings always use 0-swap for reasons given above
(funcall ,(or encode-by '#'identity) ,actual)
,enter)
,@(when end-by `((funcall (aref ,serializers 0)
(funcall ,(or encode-by '#'identity) ,actual)
,end-by)))))
(:masque `(:-masque
(funcall (aref ,serializers ,swap-by)
(masque ,actual ,@(mapcar #'masque-binder bindings))
,enter)))
(:manifest
(append
`((push (list ,qname ,index ,index) ,map))
(loop :for closure :in context
:collect `(unless (assoc ,closure ,map)
(push (list ,closure ,index ,index) ,map)))
(list name (macroexpand (append (list 'marshal (first actual) destination)
(list :-+sub-lexicon+-
(list* :pr-sym (qualify name) sub-lexicon))
(rest actual)
(getf pairs name))))
`((setf (third (assoc ,qname ,map)) ,index))
(loop :for closure :in context
:collect `(setf (third (assoc ,closure ,map)) ,index))
(loop :for slot-of :in (getf slots-of qname)
:when (not (eq :checksum-of (second slot-of)))
:collect (apply #'resolve-region qname slot-of))))
(:span
;; push a fresh per-instance region at the span's start so that
;; repeated span names across sibling sub-manifests don't collide
;; in the shared map (each instance gets its own start/end)
(append `((push (list ,qname ,index ,index) ,map))
(loop :for i :in items :append (generate i (cons qname context)))
`((setf (third (assoc ,qname ,map)) ,index))
(loop :for slot-of :in (getf slots-of qname)
:when (not (eq :checksum-of (second slot-of)))
:collect (apply #'resolve-region qname slot-of))))
(t (let ((length-form (if (not type-indicator)
length `(caddr (assoc (getf ,values ,(qualify type-indicator))
',type-conditions)))))
;; (print (list :oo name type-indicator type-conditions))
`(,qname
(push (list ,qname ,index ,index) ,map)
,@(loop :for closure :in context
:collect `(unless (assoc ,closure ,map)
(push (list ,closure ,index ,index) ,map)))
,(cond
((member :leb subtypes)
`(funcall (if signed #'encode-leb128-signed #'encode-leb128-unsigned)
(cons ,length-form
,(or (enumerate enumerate-by (getf pairs name))
default (error "Field ~a not specified." name)))
,enter))
((member :vec subtypes)
(if (getf pairs name)
`(loop :for e :across ,(getf pairs name)
:do (funcall (aref ,serializers ,swap-by)
(cons ,length-form e)
,enter))
(if length-form
`(loop :for e :below ,length-form
:do (funcall (aref ,serializers ,swap-by)
(cons ,length-form ,default)
,enter))
(error "No content or default specified for vector data."))))
((and slot (eq :checksum-of (first slot)))
`(funcall (aref ,serializers ,swap-by)
(cons ,length-form
(destructuring-bind (start end)
(rest (assoc ,(qualify (second slot)) ,map))
(funcall ,(getf slot :by) ,access start end)))
,enter))
(t `(funcall (aref ,serializers ,swap-by)
(cons ,length-form
,(or (enumerate enumerate-by (getf pairs name))
default
(and slot 0)
;; slot values do not need a default since they
;; will be populated according to other slots' values
(error "Field ~a not specified." name)))
,enter)))
(setf (third (assoc ,qname ,map)) ,index)
,@(and (getf slots-of qname)
(loop :for slot-of :in (getf slots-of qname)
:when (not (eq :checksum-of (second slot-of)))
:collect (apply #'resolve-region qname slot-of)))
,@(loop :for closure :in context
:collect `(setf (third (assoc ,closure ,map)) ,index))
(push ,(getf pairs name) ,values)
(push ,qname ,values)
;; (print (list :bi ,name ,index ,length))
))))))))
(preprocess-spec (rest spec))
(loop :for (key _) :on slots-of :by #'cddr
:unless (member key regions)
:do (error "Slot reference found with no matching region."))
(append (if (getf pairs :-+sub-lexicon+-) `(progn)
`(let* ((,access ,destination)
(,index ,(or offset 0))
(,values) ;; (,bindings-sym)
,@(if (getf params :length) `((,length ,(getf params :length))))
(,enter) (,tell) (,write) (,map)
(,serializers (make-array ,(1+ (reduce #'max swap-specs :initial-value 0)) :initial-element nil)))
(typecase ,access
(function (setf ,enter (lambda (,b) (funcall ,access ,b))
,tell (lambda () ,index)))
(vector (setf ,enter (lambda (,b) (setf (aref ,access ,index) ,b) (incf ,index))
,tell (lambda () ,index)
,write (lambda (serializer datum position)
(let ((opos ,index))
(setf ,index position)
(funcall serializer datum ,enter)
(setf ,index opos)))))
(stream (setf ,enter (lambda (,b) (incf ,index) (write-byte ,b ,access))
,tell (lambda () (file-position ,access))
,write (lambda (serializer datum position)
(let ((opos (file-position ,access)))
(file-position ,access position)
(setf ,index position)
(funcall serializer datum ,enter)
(file-position ,access opos)
(setf ,index opos))))))))
(unless (getf pairs :-+sub-lexicon+-)
(mapcar #'assign-serializer swap-specs))
(if spec (apply #'append (mapcar #'generate (rest spec)))
(error "Manifest not found."))
;; `((print (list :mmm ,map)))
(list index)
;; (print (list :v ,values))
))))
#|
;; --- enums (work today) ---
(defenum png-color-type nil :grayscale 0 :rgb 2 :palette 3 :grayscale-alpha 4 :rgba 6)
(defenum png-interlace nil :none 0 :adam7 1)
;; --- IHDR body, 13 bytes (works today as a standalone marshal) ---
(defmanifest png-ihdr (:unit 8 :endian :big)
(:width (:u 4) :default 0)
(:height (:u 4) :default 0)
(:bit-depth :u8 :default 8)
(:color-type :u8 :default 0 :enumerate-by png-color-type)
(:compression :u8 :default 0)
(:filter :u8 :default 0)
(:interlace :u8 :default 0 :enumerate-by png-interlace))
;; --- generic chunk: opaque data (span + checksum work; :length-of waits on the patch fix) ---
(defmanifest png-chunk (:unit 8 :endian :big)
(:length (:u 4) :slot (:length-of :data)) ; ⚠ patch-before, not yet functional
(span :type+data
(:type (:u 1 :vec)) ; 4-byte tag, caller-supplied
(:data (:u 1 :vec))) ; opaque bytes
(:crc (:u 4) :default 0 :slot (:checksum-of :type+data :by #'crc))) ; ✓ works
;; --- IHDR chunk: body via sub-manifest (waits on sub-manifest fixes #1/#2) ---
(defmanifest png-ihdr-chunk (:unit 8 :endian :big)
(:length (:u 4) :slot (:length-of :ihdr)) ; = 13
(span :type+data
(:type (:u 1 :vec)) ; #(73 72 68 82) "IHDR"
(manifest :png-ihdr png-ihdr)) ; ⚠ needs :name + no-let* inlining
(:crc (:u 4) :default 0 :slot (:checksum-of :type+data :by #'crc)))
;; --- whole file (waits on sub-manifest fixes) ---
(defmanifest png-file (:unit 8 :endian :big)
(:signature (:u 1 :vec)) ; caller passes the 8 magic bytes
(manifest :ihdr png-ihdr-chunk)
(manifest :idat png-idat-chunk) ; IDAT = opaque zlib blob
;; IEND, empty data
(manifest :iend png-iend-chunk))
Intended call once the fixes land:
(marshal png-ihdr-chunk buf
:type #(73 72 68 82)
:png-ihdr (:width 1 :height 1 :bit-depth 8 :color-type :rgb))
|#
;; #(55 12 0 0 0 0 5 0 2 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0)
;; #(55 12 0 0 0 0 5 0 2 0 0 0 0 0 0 0 0 0 0 5 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0)
;; #(55 12 0 0 0 0 5 0 2 0 0 0 0 0 0 0 0 0 0 5 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
;; 0 0 0 0)
(defmacro unmarshal (name destination &rest keys)
(let ((fn-sym (find-symbol (format nil "⍁UNMARSHAL-COMPOSE-~a" name)
(package-name (symbol-package name)))))
(if (fboundp fn-sym)
(apply (symbol-function fn-sym) destination keys)
(error "Manifest not found."))))
#|
(macroexpand `(defmanifest png-chunk (:unit 8 :endian :big)
(:length (:u 4) :slot (:length-of :data))
(span :type+data
(:type (:u 1 :vec))
(:data (:u 1 :vec)))
(:crc (:u 4) :slot (:checksum-of :type+data :by #'crc))))
|#
;; (defmacro make-masquer (string &rest assignments)
;; (let* ((params (if (listp (caar assignments)) (first assignments) nil))
;; (assignments (if (not params) assignments (rest assignments)))
;; (width (rest (assoc :width params)))
;; (mask (1- (ash 1 width))))
;; `(lambda (array offset)
;; (let ((bound (array-total-size array)))
;; ,(multiple-value-bind (base segments symbols) (quantify-mask-string string nil)
;; (print (list :ss base segments symbols))
;; ;; (format t "~v,'0B~%" 16 (ash (1- (ash 1 length)) (nth index segments)))
;; (let* ((base-sym 'a)
;; (rev-sym (reverse symbols))
;; (rev-seg (reverse segments))
;; (assign -1)
;; (steps (loop :for assignment :in assignments :for sym :in rev-sym
;; :for seg :in rev-seg :for n :from 0
;; :append (destructuring-bind (key value) assignment
;; (let ((index (position (intern (string-upcase key) "KEYWORD")
;; symbols))
;; (seg-length (if (= n (1- (length assignments)))
;; (nth n rev-seg)
;; (- (nth n rev-seg) (nth (1+ n) rev-seg)))))
;; (when (not index)
;; (error "Symbol ~a not found in mask ~a." key string))
;; (let ((length (- (nth (1+ index) segments)
;; (nth index segments)))
;; (divs (/ seg-length width)))
;; (print (list :ee divs length))
;; (if (= 1 divs)
;; `((setf (aref array offset) ,value)
;; (bounded-iterate offset bound))
;; (loop :for d :below divs
;; :append `((setf (aref array offset)
;; (logand (ash ,value ,(- (* 8 d)))
;; ,mask))
;; (bounded-iterate offset bound))))))))))
;; (cond ((not steps) base)
;; (t (cons 'progn steps))
;; (t `(let ((,base-sym ,base)) ,@steps ,base-sym)))))))))
;; (defmacro mqbase (name opcsym mnesym args string &body body)
;; ;; this is a currying macro for masque, allowing the creation
;; ;; of a specialized masque with static contents for some fields
;; (destructuring-bind (static-specs clauses &optional disassembler) body
;; (let ((dsarg (gensym)) (flargs (gensym))
;; (static-form (loop :for ss :in static-specs
;; :collect (if (not (eq :static (first ss)))
;; (list 'quote ss)
;; `(list :static ,@(loop :for spec :in (rest ss)
;; :collect `(list ',(first spec)
;; ,(second spec))))))))
;; `(defmacro ,name (,opcsym ,mnesym)
;; (list (list 'lambda ',(cons 'program-api args) ;; TODO - gensym for args
;; (list 'flet '((of-program (&rest ,flargs) (apply program-api ,flargs)))
;; '(declare (ignorable (function of-program)))
;; (append (list 'masque ,string)
;; ;; generate a template incorporating the :static values
;; ;; into a (masque) expansion within the defined macro
;; (list (list ,@static-form))
;; ',clauses)))
;; ,@(if (not disassembler)
;; nil `((list 'lambda (list ',dsarg 'program-api)
;; ;; '(print (list :ee program-api ,dsarg))
;; (list 'flet '((of-program (&rest ,flargs) (apply program-api ,flargs)))
;; '(declare (ignorable (function of-program)))
;; (list 'unmasque ,string ',dsarg (list ,@static-form)
;; ',(mapcar #'first clauses) ;; ',disassembler
;; (list ,@(loop :for item :in disassembler
;; :collect (if (and (symbolp item)
;; (eql item mnesym))