-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrivial-formatter.lisp
1725 lines (1538 loc) · 67.1 KB
/
trivial-formatter.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
(in-package :cl-user)
(defpackage :trivial-formatter
(:use :cl)
(:export ;; Main api
#:fmt
;; Useful helpers
#:read-as-code
#:print-as-code
;; Readtable name.
#:as-code
;; Special variable
#:*external-formatters-directories*
#:*strict-loop-keyword-p*))
(in-package :trivial-formatter)
(declaim (optimize speed))
;;;; *EXTERNAL-FORMATTERS-DIRECTORIES*
(declaim
(type list ; of-type directories.
*local-project-directories* *external-formatters-directories*))
(defvar *local-project-directories*
;; QUICKLISP and ROSWELL may not exist in the user environment.
`(,@(when (find-package '#:ql)
(symbol-value
(uiop:find-symbol* '#:*local-project-directories* '#:ql)))
,@(when (find-package '#:roswell)
(symbol-value
(uiop:find-symbol* '#:*local-project-directories* '#:roswell))))
"List of local project directory pathnames. Used to search external formatters.")
(defparameter *external-formatters-directories*
(loop :for directory :in *local-project-directories*
:collect directory ; For backward complatibility.
:collect (merge-pathnames "external-formatter/" directory))
"List of external-formatter directory pathnames. Used to search external formatter.")
(defun check-deprecated (directory)
"Signal warning when formatter.lisp exists directly under local-project-directory."
(let ((local-project-directory
(find (pathname-directory directory) *local-project-directories*
:test #'equal
:key #'pathname-directory)))
(when local-project-directory
(warn
(formatter
#.(concatenate 'string
"Placing formatter.lisp to directly under ~S is deprecated from version 10."
"~:@_Move it to ~S is recommended."))
local-project-directory
(merge-pathnames "external-formatter/" local-project-directory))
;; As penalty. May be increased in the future.
(sleep 1))))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Compiler claims as undefined variable unless this eval-when.
(unless (boundp '+last-updates+)
(defconstant +last-updates+
(merge-pathnames ".last-updates"
(asdf:system-source-directory
(asdf:find-system :trivial-formatter))))))
(defvar *last-updates*
nil
"Hash-table of { pathname:finxum } as external-formatter file path: last update timestamp.")
(defun save-last-updates-table (&optional (*last-updates* *last-updates*))
(cl-store:store *last-updates* +last-updates+))
(eval-when (:load-toplevel)
;; Initialize .last-updates table file.
(unless (probe-file +last-updates+)
(save-last-updates-table (make-hash-table :test #'equal))))
(defun load-last-updates-table (&optional (path +last-updates+))
(let ((table (cl-store:restore path)))
(loop :for external-formatter :being :each :hash-key :of table
:do (load external-formatter))
table))
(defun time-last-updated (external-formatter)
;; As abstract barrier.
(gethash external-formatter *last-updates*))
(defun (setf time-last-updated) (time external-formatter)
;; As abstract barrier.
(setf (gethash external-formatter *last-updates*) time))
(defmacro with-updates-last-updates ((var <data-file-path>) &body body)
(let ((?toplevelp (gensym "TOPLEVELP")))
`(let* ((,?toplevelp)
(,var
(or *last-updates*
(setq ,?toplevelp t
*last-updates*
(load-last-updates-table ,<data-file-path>)))))
(unwind-protect (progn ,@body)
(and ,?toplevelp (save-last-updates-table ,var))))))
(defun should-load-p
(external-formatter &optional (*last-updates* *last-updates*))
(let ((last-update-cache (time-last-updated external-formatter)) last-update)
(flet ((time-file-wrote (external-formatter)
(uiop:safe-file-write-date (truename external-formatter))))
(cond ;; Does not exists in cache table.
((not last-update-cache)
(setf (time-last-updated external-formatter)
(time-file-wrote external-formatter))
t)
;; External-formatter is updated.
((uiop:timestamp< last-update-cache
(setq last-update
(time-file-wrote external-formatter)))
(setf (time-last-updated external-formatter) last-update)
t)
;; External-formatter is newest.
(t nil)))))
(defclass external-formatter (asdf:cl-source-file) ())
(defmethod asdf:input-files ((o asdf:compile-op) (c external-formatter))
(list (asdf:component-pathname c)))
(defun load-external-formatters ()
"Load all external formatters."
;; FIXME: [DONE!] Should we compile it?
;; : [DONE!] Should we check file hash or timestamp to skip?
;; : Should we bind *load-verbose* and/or *load-print*?
;; : Should we search formatters.lisp recursively?
;; FIXME: <del>3rd</del>18st slow profile report.
(with-updates-last-updates (table +last-updates+)
(loop :for directory :in *external-formatters-directories*
:for pathname := (merge-pathnames "formatters.lisp" directory)
:when (probe-file pathname)
:do (check-deprecated pathname)
(when (should-load-p pathname table)
(let ((external-formatter
(make-instance 'external-formatter :name "dummy")))
(setf (slot-value external-formatter
'asdf::absolute-pathname)
pathname)
(asdf::perform-lisp-compilation
(asdf:make-operation 'asdf:compile-op)
external-formatter)
(asdf::perform-lisp-load-fasl
(asdf:make-operation 'asdf:load-op)
external-formatter))))))
;;;; DEFORMTTER
(defmacro deformatter (package symbol &body body)
"(deformatter package symbol (stream-var exp-var) &body body)
Define formatter function."
(declare (type symbol package symbol))
(let ((pprinter (gensym (format nil "PPRINT-~A" symbol))))
`(when (find-package ,(string package))
(defun ,pprinter ,@body)
(set-pprint-dispatch
`(cons
(member ,(uiop:find-symbol* ,(string symbol) ,(string package))))
',pprinter)
',pprinter)))
(defun pprint-deformatter (stream exp)
(setf stream (or stream *standard-output*))
(funcall
(formatter "~:<~W~^ ~3I~@_~W~^ ~@_~W~^ ~@_~W~1I~^~@:_~@{~W~^~:@_~}~:>")
stream exp))
(set-pprint-dispatch '(cons (member deformatter)) 'pprint-deformatter)
;;;; FMT
(declaim
(ftype (function (asdf:component)
(values list ; of-type asdf:cl-source-file
&optional))
component-children))
(defun component-children (component)
"List up all cl-source-file components of the COMPONENT."
(labels ((rec (list acc primary-system-name)
(if (endp list)
acc
(body (car list) (cdr list) acc primary-system-name)))
(secondary-systems (first primary-system-name)
(loop :for system :in (asdf:system-depends-on first)
:if (equal primary-system-name
(asdf:primary-system-name system))
:collect (asdf:find-system system)))
(cl-source-file-p (first)
(let ((class
(asdf/component:module-default-component-class first)))
(and class (eq 'asdf:cl-source-file (class-name class)))))
(absolute-pathname (c)
(slot-value c 'asdf/component:absolute-pathname))
(body (first rest acc primary-system-name)
(typecase first
(asdf:package-inferred-system
(rec (nconc (secondary-systems first primary-system-name) rest)
(if (cl-source-file-p first)
(union (asdf:component-children first) acc
:test #'equal
:key #'absolute-pathname)
acc)
primary-system-name))
(asdf:system
(rec (append (asdf:component-children first) rest) acc
primary-system-name))
(asdf:module
(rec (append (asdf:component-children first) rest) acc
primary-system-name))
(asdf:cl-source-file
(rec rest (cons first acc) primary-system-name))
(otherwise (rec rest acc primary-system-name)))))
(rec (list component) nil
(when (typep component 'asdf:package-inferred-system)
(asdf:primary-system-name component)))))
(declaim
(ftype (function
((or symbol string asdf:system) &optional
(member nil :append
:supersede :rename
:error :new-version
:rename-and-delete :overwrite))
(values null &optional))
fmt))
(defun fmt (system &optional (if-exists nil))
"Format every source code of the SYSTEM.
IF-EXISTS is a same value of the same parameter of CL:OPEN."
;; FIXME: 2nd slow profile report, especially consing.
;; Can we pooling the objects?
;;;
;; In order to know function/macro definitions of the dependencies.
;; Additionally, in order to ignore component order, we need to load the whole SYSTEM beforehand.
(asdf:load-system system)
(load-external-formatters)
(dolist (component (component-children (asdf:find-system system)))
(if (null if-exists)
(debug-printer component)
(let ((string
;; In order to open file for superseding,
;; we need to close it beforehand.
(with-output-to-string (*standard-output*)
(debug-printer component))))
(with-open-file (out (asdf:component-pathname component) :direction :output
:if-does-not-exist :create
:if-exists if-exists)
(write-string string out))))))
;;;; READ-AS-CODE
(declaim
(ftype (function (simple-string) (values simple-string &optional))
canonicalize-case))
(defun canonicalize-case (string)
"Destructively canonicalize STRING case."
(flet ((convert-all (converter)
(do ((new string)
(index 0))
((not (array-in-bounds-p string index)) new)
(case (char string index)
(#\\ ; single escape.
(incf index 2))
(#\| ; multiple escape.
(incf index)
(do ((char (char string index) (char string index)))
((char= #\| char) (incf index))
(incf index
(if (char= #\\ char) ; single escape.
2
1))))
(otherwise
(setf (aref new index)
(locally ; due to not know base-char.
#+sbcl
(declare
(sb-ext:muffle-conditions sb-ext:compiler-note))
(funcall converter (char string index))))
(incf index))))))
(ecase (readtable-case *readtable*)
((:upcase :downcase) (convert-all #'char-downcase))
((:preserve :invert) string))))
(defvar *brokens* nil "List of marked symbols.")
(defun mark-it (symbol notation)
"Mark symbol as broken notation."
(setf (get symbol 'notation) notation)
(push symbol *brokens*)
symbol)
(defun make-broken-symbol (notation)
"Make symbol that is used placeholder for broken symbol notation."
(let ((symbol (gensym)))
(setf (symbol-function symbol) #'make-broken-symbol) ; as dummy.
(mark-it symbol notation)))
(declaim
(ftype (function
(character simple-string &key (:start (mod #.array-total-size-limit)))
(values (or boolean (mod #.array-total-size-limit)) &optional))
index-of))
(defun index-of (char string &key (start 0))
"Almost same cl:position but ignore escaped one."
(do ((index start (1+ index))
(length (length string)))
((not (< index length)) nil)
(declare (type (mod #.array-total-size-limit) index))
(let ((c (char string index)))
(cond ((char= #\\ c) (incf index))
((char= char c) (return index))
(t #|Do nothing, next loop.|#)))))
(declaim
(ftype (function (t simple-string) (values boolean &optional)) valid-value-p))
(defun valid-value-p (thing notation)
"Is not NOTATION broken?"
(or (not (symbolp thing))
(keywordp thing)
(null (symbol-package thing))
(and (nth-value 1 (find-symbol (symbol-name thing)))
;; If programmer specify :: explicity, there may a reason.
;; We should keep it.
(not (search "::" notation))
(or (not (index-of #\: notation))
(locally ; due to not known base-char
#+sbcl
(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(every #'char-equal (package-name (symbol-package thing))
notation))))))
(eval-when (:compile-toplevel :load-toplevel)
;; This is used read-time evaluation so eval-when is needed.
(defun implementation-dependent-condition ()
;; Implementation dependent condition may change in the future.
;; We choose to use dynamic value rather than static symbol.
(loop :for i :of-type fixnum :upfrom 1
:for package-name = (format nil "~@R" i)
:unless (find-package package-name)
:return (handler-case
(read-from-string (format nil "~@R:symbol" i))
(condition (c)
(let ((type (type-of c)))
(when (subtypep type 'package-error)
(warn "~S should be fixed to use default clause."
'read-from-notation))
type))
(:no-error (&rest results)
(error "Internal error: Must never reached here. ~S"
results))))))
(defun read-from-notation (notation)
(handler-case (values (read-from-string notation))
#+ecl
(#.(implementation-dependent-condition) (c)
(if (search "There is no package with the name" (princ-to-string c))
(make-broken-symbol notation)
(error c)))
#+allegro
(#.(implementation-dependent-condition) (c)
(if (search "Package " (princ-to-string c))
(make-broken-symbol notation)
(error c)))
#+cmucl
(#.(implementation-dependent-condition) ()
(make-broken-symbol notation))
#+abcl
(#.(implementation-dependent-condition) (c)
(if (search "can't be found." (princ-to-string c) :from-end t)
(make-broken-symbol notation)
(error c)))
;; The default.
(package-error ()
(make-broken-symbol notation))
(:no-error (value)
(unless (valid-value-p value notation)
(mark-it value notation))
value)))
(defun %read-as-code
(*standard-input* &optional (eof-error-p t) eof-value recursive-p)
;; The body of READ-AS-CODE.
;; For efficiency, strip away the environment achieving part.
(handler-case (peek-char t)
(end-of-file (c)
(if eof-error-p
(error c)
eof-value))
(:no-error (char)
(if (named-readtables::%get-macro-character char *readtable*)
(read *standard-input* eof-error-p eof-value recursive-p)
(let ((notation
(canonicalize-case
(read-as-string:read-as-string nil eof-error-p eof-value
recursive-p))))
#+abcl
(when (uiop:string-prefix-p "::" notation)
(setq notation (subseq notation 1)))
(if (every (lambda (c) (char= #\. c)) notation)
(make-dot :notation notation)
(read-from-notation notation)))))))
(declaim
(ftype (function (&optional (or null stream) boolean t boolean)
(values t &optional))
read-as-code))
(defun read-as-code
(&optional stream (eof-error-p t) (eof-value nil) (recursive-p nil))
;; FIXME: 3rd slow profile report.
;; Cas we pool readtable?
"Same with CL:READ but return intermediate S-Expression as lisp source code."
#+abcl
(check-type eof-error-p boolean)
(let* ((*readtable*
(handler-bind ((named-readtables:reader-macro-conflict #'continue))
(named-readtables:merge-readtables-into (copy-readtable)
(named-readtables:copy-named-readtable
'as-code))))
(*standard-input* (or stream *standard-input*)))
(%read-as-code *standard-input* eof-error-p eof-value recursive-p)))
(defun cleanup-brokens ()
(dolist (symbol *brokens*) (remprop symbol 'notation))
(setf *brokens* nil))
;;;; META-OBJECT
;;; DOT
(defstruct dot notation)
(defmethod print-object ((dot dot) stream)
(write-string (dot-notation dot) stream))
;;; COMMENT
(defstruct comment content)
(defstruct (line-comment (:include comment)))
(defmethod print-object ((c line-comment) stream)
(if (uiop:string-prefix-p #\; (comment-content c))
(funcall (formatter "~:@_;~A") stream (comment-content c))
(funcall (formatter "~:@_; ~A") stream (comment-content c)))
(pprint-newline :mandatory stream)
;; Placeholder for end of line comment.
(write-char #\Nul stream))
(defstruct (block-comment (:include comment)))
(defmethod print-object ((c block-comment) stream)
(funcall (formatter "~A") stream (comment-content c)))
;;; CONDITIONAL
(defstruct conditional char condition)
(defmethod print-object ((c conditional) stream)
(funcall (formatter "~_#~A~A") stream (conditional-char c)
(conditional-condition c)))
;;; READ-TIME-EVAL
(defstruct read-time-eval form)
(defmethod print-object ((form read-time-eval) stream)
(funcall (formatter "~<#.~;~W~:>") stream (list (read-time-eval-form form))))
;;; SHARED-OBJECT
(defstruct shared-object number exp)
(defmethod print-object ((obj shared-object) stream)
(funcall (formatter "#~D=~S") stream (shared-object-number obj)
(shared-object-exp obj)))
;;; SHARED-REFERENCE
(defstruct shared-reference number)
(defmethod print-object ((ref shared-reference) stream)
(funcall (formatter "#~D#") stream (shared-reference-number ref)))
;;; COMMA
(defstruct comma sub-char form)
(defmethod print-object ((c comma) stream)
(let (#+sbcl (sb-pretty:*pprint-quote-with-syntactic-sugar* t))
(funcall (formatter ",~@[~C~]~W") stream (comma-sub-char c)
(comma-form c))))
;;; BACKQUOTE
(defstruct backquote form)
(defmethod print-object ((b backquote) stream)
(funcall (formatter "`~W") stream (backquote-form b)))
;;;; RADIX
(defstruct radix char radix number)
(defmethod print-object ((r radix) stream)
(funcall (formatter "#~C~VR") stream (radix-char r) (radix-radix r)
(radix-number r)))
;;;; MACRO CHARS
(defun |paren-reader| (stream character)
(declare (ignore character))
(loop :for char = (peek-char t stream)
;; end check.
:if (char= #\) char)
:do (read-char stream)
(loop-finish)
;; The default.
:else
:collect (%read-as-code stream t t t)))
(defun |line-comment-reader| (stream character)
(declare (ignore character))
(make-line-comment :content (string-trim " "
(the simple-string
(read-line stream)))))
(declaim
(ftype (function
(stream base-char (or null (integer 0 #.most-positive-fixnum)))
(values t &optional))
|block-comment-reader|
|#+-reader|
|#.reader|
|#=reader|
|##reader|
|#'reader|
|radix-reader|))
(defun |block-comment-reader| (stream character number)
(make-block-comment :content (with-output-to-string (*standard-output*)
(funcall #'read-as-string::|#\|reader| stream
character number))))
(defun |#+-reader| (stream character number)
(when number
(warn "A numeric argument is ignored in #~A~A." number character))
(make-conditional :char character :condition (%read-as-code stream)))
(defun |#.reader| (stream character number)
(declare (ignore character))
(when number
(warn "A numeric argument is ignored in read time eval."))
(make-read-time-eval :form (%read-as-code stream t t t)))
(defun |#=reader| (stream character number)
(declare (ignore character))
(make-shared-object :number number :exp (%read-as-code stream)))
(defun |##reader| (stream character number)
(declare (ignore stream character))
(make-shared-reference :number number))
(defun |'reader| (stream character)
(declare (ignore character))
(list* 'quote (list (%read-as-code stream))))
(defun |#'reader| (stream character number)
(declare (ignore character))
(when number
(warn "Ignore numeric argument for #~D'." number))
(list* 'function (list (%read-as-code stream))))
(defun |radix-reader| (stream character number)
(let ((integer
(funcall
(coerce
(get-dispatch-macro-character #\# character (copy-readtable nil))
'function)
stream character number)))
(make-radix :char (char-downcase character)
:radix (ecase character
((#\b #\B) 2)
((#\o #\O) 8)
((#\x #\X) 16)
((#\r #\R) number))
:number integer)))
(defun |,reader| (stream character)
(declare (ignore character))
(let ((sub-char (peek-char t stream)))
(make-comma :sub-char (when (find sub-char '(#\. #\@))
(read-char stream))
:form (%read-as-code stream))))
(defun |`reader| (stream character)
(declare (ignore character))
(make-backquote :form (%read-as-code stream)))
;;;; NAMED-READTABLE
(locally
;; due to named-readtables, out of scope.
#+sbcl
(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(named-readtables:defreadtable as-code
(:merge :common-lisp)
(:macro-char #\( '|paren-reader|)
(:macro-char #\; '|line-comment-reader|)
(:macro-char #\' '|'reader|)
(:macro-char #\` '|`reader|)
(:macro-char #\, '|,reader|)
(:dispatch-macro-char #\# #\| '|block-comment-reader|)
(:dispatch-macro-char #\# #\+ '|#+-reader|)
(:dispatch-macro-char #\# #\- '|#+-reader|)
(:dispatch-macro-char #\# #\. '|#.reader|)
(:dispatch-macro-char #\# #\' '|#'reader|)
(:dispatch-macro-char #\# #\= '|#=reader|)
(:dispatch-macro-char #\# #\# '|##reader|)
(:dispatch-macro-char #\# #\B '|radix-reader|)
(:dispatch-macro-char #\# #\O '|radix-reader|)
(:dispatch-macro-char #\# #\X '|radix-reader|)
(:dispatch-macro-char #\# #\R '|radix-reader|)))
(defun init-table ()
;; FIXME: 1st slow profile report.
;; Can we pooling the pprint-dispatch?
(let ((*print-pprint-dispatch* (copy-pprint-dispatch)))
(set-pprint-dispatch '(eql #\Space) (formatter "#\\~:C"))
(set-pprint-dispatch 'symbol 'symbol-printer)
(set-pprint-dispatch '(cons (member handler-case)) 'pprint-handler-case)
(set-pprint-dispatch '(cons (member loop)) 'pprint-extended-loop)
(set-pprint-dispatch '(cons (member define-condition))
'pprint-define-condition)
(set-pprint-dispatch '(cons (member or and values)) 'pprint-linear-elt)
(set-pprint-dispatch '(cons (member flet labels macrolet)) 'pprint-flet)
(set-pprint-dispatch '(cons (member when unless)) 'pprint-when)
(set-pprint-dispatch '(cons (member restart-case)) 'pprint-restart-case)
(set-pprint-dispatch '(cons (member restart-bind)) 'pprint-restart-bind)
(set-pprint-dispatch '(cons (member cond)) 'pprint-cond)
(set-pprint-dispatch '(cons (member with-open-file))
'pprint-with-open-file)
(set-pprint-dispatch '(cons (member ftype)) 'pprint-ftype)
(set-pprint-dispatch '(cons (member assert)) 'pprint-assert)
(set-pprint-dispatch '(cons (member defclass)) 'pprint-defclass)
(set-pprint-dispatch '(cons (member define-compiler-macro))
(pprint-dispatch '(defun) nil))
(set-pprint-dispatch '(cons (member defstruct)) 'pprint-defstruct)
(set-pprint-dispatch '(cons (member defgeneric)) 'pprint-defgeneric)
(set-pprint-dispatch '(cons (member pushnew)) 'pprint-fun-call)
(set-pprint-dispatch '(cons (member dynamic-extent))
'pprint-dynamic-extent)
*print-pprint-dispatch*))
(defparameter *pprint-dispatch* (init-table))
(defun string-as-code (exp)
"Return lisp source code string of the EXP."
(let* ((*print-case* :downcase)
(*print-pprint-dispatch* (init-table))
(*pprint-dispatch* (init-table))
(*print-pretty* t)
(*print-level*)
(*print-length*)
(*print-lines*))
(set-pprint-dispatch 'list 'pprint-list)
(prin1-to-string exp)))
(declaim
(ftype (function
(character simple-string &key (:start (mod #.array-total-size-limit)))
(values (mod #.array-total-size-limit) &optional))
delimited-position))
(defun delimited-position (delimiter string &key (start 0))
"Position of the next DELIMITER. Unlike CL:POSITION, skip escaped one."
(or (index-of delimiter string :start start)
(error "Missing delimiter ~S in ~S" delimiter string)))
(eval-when (:compile-toplevel :load-toplevel)
(define-symbol-macro can-declare-fixnum
(if (< array-total-size-limit most-positive-fixnum)
'(:and)
'(:or))))
(let ((line (make-string-output-stream)) temp)
(defun split-to-lines (string)
"List of lines with handling escaped newline."
(declare (optimize speed)
(type simple-string string))
(flet ((sieve (line)
(let ((line
;; Cleanup placeholder for end of line comment.
(delete #\Nul
(the simple-string
(ppcre:regex-replace
#.(format nil "~C " #\Nul) line "")))))
;; Skip empty line.
(unless (every (lambda (char) (char= #\Space char)) line)
(list line)))))
(declare
(ftype (function (simple-string) (values list &optional)) sieve))
(loop :for index
#+#.trivial-formatter::can-declare-fixnum :of-type
#+#.trivial-formatter::can-declare-fixnum (integer 0
#.most-positive-fixnum)
= 0 :then (1+ index)
:for char
:= (when (array-in-bounds-p string index)
(aref string index))
:if (null char)
:if (and (setf temp (sieve (get-output-stream-string line)))
(string= "" (the string (car temp))))
:do (loop-finish)
:else
:nconc temp
:and :do (loop-finish)
:else :if (char= #\\ char)
:do (write-char char line)
(write-char (aref string (incf index)) line)
:else :if (find char "\"|")
:do (let ((end
(delimited-position char string :start (1+ index))))
(write-string string line :start index :end (1+ end))
(setf index end))
:else :if (char= #\; char)
:nconc (let ((end (position #\Newline string :start (1+ index))))
(prog1 (sieve (subseq string index end))
(if end
(setf index end)
(setf index (1+ array-total-size-limit)))))
:and :do (get-output-stream-string line) ; discard gabage.
:else :if (char= #\Newline char)
:nconc (sieve (get-output-stream-string line))
:else
:do (write-char char line)))))
(declaim
(ftype (function (simple-string)
(values (mod #.array-total-size-limit) &optional))
count-indent))
(defun count-indent (string)
"Count indent speces."
(loop :for char :across string
:while (char= #\Space char)
:count char))
(defun alignment (list)
"Align indent especially for comment."
(labels ((rec (list &optional acc)
(if (endp list)
acc
(body (car list) (cdr list) acc)))
(body (first rest acc)
(if (and rest (ppcre:scan "^ *;;" (the simple-string (car rest))))
(rec (cons (set-align first (car rest)) (cdr rest))
(cons first acc))
(rec rest (cons first acc))))
(set-align (current comment)
(let* ((indent (count-indent current))
(start2 (count-indent comment))
(comment-length (- (length comment) start2))
(string
(make-string (+ indent comment-length)
:initial-element #\Space)))
;; due to not simple-base-string.
#+sbcl
(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(replace string comment :start1 indent :start2 start2)
string)))
(declare
(ftype (function (simple-string simple-string)
(values simple-string &optional))
set-align))
(rec (reverse list))))
(declaim
(ftype (function (function (simple-array character (*)) &optional stream)
(values null &optional))
write-string-from))
(defun write-string-from
(pred string &optional (*standard-output* *standard-output*))
(let ((pos (position-if pred string)))
(when pos
(write-string string nil :start pos)))
nil)
;;;; PRINT-AS-CODE
(deftype stream-designator () '(or (eql t) null stream #+abcl xp::xp-structure))
(defun output-stream (stream-designator)
(etypecase stream-designator
(null *standard-output*)
((eql t) *terminal-io*)
(stream stream-designator)
#+abcl
(xp::xp-structure stream-designator)))
(defun single-semicoloned-line-comment-line-p (line)
(ppcre:scan "^ *(; |;$)" line))
(declaim
(ftype (function (t &optional stream-designator) (values null &optional))
print-as-code))
(defun print-as-code (exp &optional stream)
"Print EXP as lisp source code to STREAM."
(let ((*standard-output* (output-stream stream)) (*print-circle*))
(if (typep exp '(or block-comment string))
(tagbody (prin1 exp))
(loop :for (first . rest) :of-type (simple-string . list)
:on (alignment (split-to-lines (string-as-code exp)))
:if (and rest
(single-semicoloned-line-comment-line-p
(the simple-string (car rest))))
:if (single-semicoloned-line-comment-line-p first)
;; Both are single semicoloned line comment.
;; Integrate it as one for pritty printings.
:do (setf (car rest) (format nil "~A ~A" first (car rest)))
:else
;; Next one is single semicoloned line comment but FIRST.
;; Both should be printed in same line.
:do (format t "~A " first)
(rplaca rest
(string-left-trim " "
(the simple-string (car rest))))
:else :if (single-semicoloned-line-comment-line-p first)
;; Next is not single semicoloned line comment but FIRST.
;; Comment should be printed.
:do (funcall (formatter "~<;~@;~@{~^ ~A~^ ~:_~}~:>~:[~;~%~]")
*standard-output*
(delete "" (the list (ppcre:split "; ?" first))
:test #'equal)
rest) ; To avoid unneeded newline.
;; Both are not single semicoloned line comment.
:else :if (null rest)
;; Last line never need newline.
:do (write-string first)
:else :if (ppcre:scan "[^\\\\]\\($" first)
;; To avoid unneeded newline. Especially &KEY.
:do (rplaca rest
(with-output-to-string (*standard-output*)
(write-string first)
(write-string-from
(lambda (c) (not (char= #\Space c)))
(car rest))))
:else :if (= (1+ (length first)) (count-indent (car rest)))
;; To avoid unneeded newline. Especially for conditional.
:do (rplaca rest
(with-output-to-string (*standard-output*)
(write-string first)
(write-char #\Space)
(write-string-from
(lambda (c) (not (char= #\Space c)))
(car rest))))
:else
:do (write-line first)))))
;;;; DEBUG-PRINTER
(defun debug-printer (component)
"Print formatted lisp source code of the COMPONENT."
(let ((package *package*))
(unwind-protect
(with-open-file (input (asdf:component-pathname component))
(loop :with tag = '#:end
:for exp = (read-as-code input nil tag) :then next
:with next
:until (eq exp tag)
:do (let* ((*print-length*)
(string
(with-output-to-string (s)
(unwind-protect (print-as-code exp s)
(cleanup-brokens)))))
;; In order to refer macro symbol for correct indent,
;; we need to eval IN-PACKAGE.
(when (listp exp) ; ignore top level conditional.
(let ((exp
(ignore-errors (read-from-string string nil))))
(when (typep exp '(cons (eql in-package)))
;; Eval only top-level IN-PACKAGE.
;; We believe no macro expanded into IN-PACKAGE.
(eval exp))))
(write-string string))
(setf next (read-as-code input nil tag))
(when (typep exp 'conditional)
(terpri)
(unwind-protect (print-as-code next) (cleanup-brokens))
(setf exp next
next (read-as-code input nil tag)))
(cond ((block-comment-p exp) (format t "~2%"))
((line-comment-p exp)
(format t "~%~:[~%~;~]" (comment-p next)))
((eq next tag)) ; Do nothing.
((not (line-comment-p next)) (format t "~2%"))
((uiop:string-prefix-p #\; (comment-content next))
(format t "~2%"))
(t (write-char #\Space)))))
(setf *package* package))))
;;;; PRETTY PRINTERS
(defun pprint-defclass (stream exp)
(setf stream (output-stream stream))
(funcall
(formatter
#.(concatenate 'string "~:<" ; pprint-block.
"~W~^ ~3I~@_" ; operator
"~W~^ ~@_" ; class-name
"~:<~@{~W~^ ~@_~}~:>~^ ~1I~:_" ; superclasses
"~:<~@{~/trivial-formatter::pprint-fun-call/~^ ~_~}~:>~^ ~_" ; slots
"~@{~W~^ ~_~}" ; options
"~:>"))
stream exp))
(defun pprint-ftype (stream exp)
(setf stream (output-stream stream))
(funcall (formatter "~:<~W~^ ~1I~@_~:I~^~W~^ ~_~@{~W~^ ~_~}~:>") stream exp))
(defun pprint-dynamic-extent (output exp)
(setf output (output-stream output))
(funcall (formatter "~:<~W~^ ~@_~@{~:<~W~^ ~@{~W~^ ~}~:>~^ ~}~:>") output
exp))
(declaim
(ftype (function (package) (values simple-string &optional))
shortest-package-name))
(defun shortest-package-name (package)
(flet ((compare (champion challenger)
(if (< (length champion) (length challenger))
champion
challenger)))
(declare
(ftype (function (simple-string simple-string)
(values simple-string &optional))
compare))
(reduce #'compare (package-nicknames package)
:initial-value (package-name package))))
(let ((default-pprint-dispatch (copy-pprint-dispatch nil)))
(defun symbol-printer (stream object)
(let ((notation (get object 'notation)))
(if notation
(write-string notation stream)
(let ((default-style
(let ((*print-pprint-dispatch* default-pprint-dispatch))
(prin1-to-string object))))
(if (or (null (symbol-package object))
(eq #.(find-package :keyword) (symbol-package object))
(nth-value 1 (find-symbol (symbol-name object))))
(write-string default-style stream)
(progn
(loop :for char
:across (shortest-package-name
(symbol-package object))
:do (write-char
(locally
;; due to uncertainty base-char or not.
#+sbcl
(declare
(sb-ext:muffle-conditions sb-ext:compiler-note))
(char-downcase char))
stream))
(write-string default-style stream
:start (or (index-of #\: default-style)
(error
"Internal logical error: Missing colon in ~S."
default-style))))))))))
(defun pprint-handler-case (stream exp &rest noise)
(declare (ignore noise))
(setf stream (output-stream stream))
(funcall
(formatter
#.(concatenate 'string "~:<" ; pprint-logical-block
"~W~^ ~3I~:_" ; operator
"~W~^ ~1I~_" ; form
(concatenate 'string "~@{" ; cluases.
(concatenate 'string "~:<" ; each clause
; logical-block.
"~W~^ ~@_" ; condition.
"~:<~@{~W~^ ~@_~}~:>~^ ~1I~:@_" ; lambda-list
"~@{~W~^ ~_~}" ; clause-body
"~:>")
"~^ ~_~}")
"~:>"))
stream exp))