-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkernel.scm
2472 lines (2281 loc) · 101 KB
/
kernel.scm
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
;;; SPDX-FileCopyrightText: 2005 - 2013 Alan Manuel K. Gloria
;;; SPDX-FileCopyrightText: 2005 - 2013 David A. Wheeler
;;;
;;; SPDX-License-Identifier: MIT
;;; kernel.scm
;;; Implementation of the sweet-expressions project by readable mailinglist.
;;;
;;; Copyright (C) 2005-2013 by David A. Wheeler and Alan Manuel K. Gloria
;;;
;;; This software is released as open source software under the "MIT" license:
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a
;;; copy of this software and associated documentation files (the "Software"),
;;; to deal in the Software without restriction, including without limitation
;;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;;; and/or sell copies of the Software, and to permit persons to whom the
;;; Software is furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included
;;; in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
;;; OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
;;; ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;;; OTHER DEALINGS IN THE SOFTWARE.
;;; Warning: For portability use eqv?/memv (not eq?/memq) to compare characters.
;;; A "case" is okay since it uses "eqv?".
;;; This file includes:
;;; - Compatibility layer - macros etc. to try to make it easier to port
;;; this code to different Scheme implementations (to deal with different
;;; module systems, how to override read, getting position info, etc.)
;;; - Re-implementation of "read", beginning with its support procedures.
;;; There is no standard Scheme mechanism to override just *portions*
;;; of read, and we MUST make {} delimiters, so we have to re-implement read.
;;; We also need to get control over # so we know which ones are comments.
;;; If you're modifying a Scheme implementation, just use that instead.
;;; - Curly Infix (c-expression) implementation
;;; - Neoteric expression (n-expression) implementation
;;; - Sweet-expression (t-expression) implementation
;;; - Implementation of writers for curly-infix and neoteric expressions -
;;; a "-simple" implementation, and a separate -shared/-cyclic version.
;;; The "-simple" one is separate so that you can use just it.
;;; Note that a lot of the code is in the compatibility layer and
;;; re-implementation of "read"; implementing the new expression languages
;;; is actually pretty easy.
; -----------------------------------------------------------------------------
; Compatibility Layer
; -----------------------------------------------------------------------------
; The compatibility layer is composed of:
;
; (readable-kernel-module-contents (exports ...) body ...)
; - a macro that should package the given body as a module, or whatever your
; scheme calls it (chicken eggs?), preferably with one of the following
; names, in order of preference, depending on your Scheme's package naming
; conventions/support
; (readable kernel)
; readable/kernel
; readable-kernel
; sweetimpl
; - The first element after the module-contents name is a list of exported
; procedures. This module shall never export a macro or syntax, not even
; in the future.
; - If your Scheme requires module contents to be defined inside a top-level
; module declaration (unlike Guile where module contents are declared as
; top-level entities after the module declaration) then the other
; procedures below should be defined inside the module context in order
; to reduce user namespace pollution.
;
; (my-peek-char port)
; (my-read-char port)
; - Performs I/O on a "port" object.
; - The algorithm assumes that port objects have the following abilities:
; * The port automatically keeps track of source location
; information. On R5RS there is no source location
; information that can be attached to objects, so as a
; fallback you can just ignore source location, which
; will make debugging using sweet-expressions more
; difficult.
; - "port" or fake port objects are created by the make-read procedure
; below.
;
; (make-read procedure)
; - The given procedure accepts exactly 1 argument, a "fake port" that can
; be passed to my-peek-char et al.
; - make-read creates a new procedure that supports your Scheme's reader
; interface. Usually, this means making a new procedure that accepts
; either 0 or 1 parameters, defaulting to (current-input-port).
; - If your Scheme doesn't keep track of source location information
; automatically with the ports, you may again need to wrap it here.
; - If your Scheme needs a particularly magical incantation to attach
; source information to objects, then you might need to use a weak-key
; table in the attach-sourceinfo procedure below and then use that
; weak-key table to perform the magical incantation.
;
; (invoke-read read port)
; - Accepts a read procedure, which is a (most likely built-in) procedure
; that requires a *real* port, not a fake one.
; - Should unwrap the fake port to a real port, then invoke the given
; read procedure on the actual real port.
;
; (get-sourceinfo port)
; - Given a fake port, constructs some object (which the algorithm treats
; as opaque) to represent the source information at the point that the
; port is currently in.
;
; (attach-sourceinfo pos obj)
; - Attaches the source information pos, as constructed by get-sourceinfo,
; to the given obj.
; - obj can be any valid Scheme object. If your Scheme can only track
; source location for a subset of Scheme object types, then this procedure
; should handle it gracefully.
; - Returns an object with the source information attached - this can be
; the same object, or a different object that should look-and-feel the
; same as the passed-in object.
; - If source information cannot be attached anyway (your Scheme doesn't
; support attaching source information to objects), just return the
; given object.
;
; (replace-read-with f)
; - Replaces your Scheme's current reader.
; - Replace 'read and 'get-datum at the minimum. If your Scheme
; needs any kind of involved magic to handle load and loading
; modules correctly, do it here.
;
; (parse-hash no-indent-read char fake-port)
; - a procedure that is invoked when an unrecognized, non-R5RS hash
; character combination is encountered in the input port.
; - this procedure is passed a "fake port", as wrapped by the
; make-read procedure above. You should probably use my-read-char
; and my-peek-char in it, or at least unwrap the port (since
; make-read does the wrapping, and you wrote make-read, we assume
; you know how to unwrap the port).
; - if your procedure needs to parse a datum, invoke
; (no-indent-read fake-port). Do NOT use any other read procedure. The
; no-indent-read procedure accepts exactly one parameter - the fake port
; this procedure was passed in.
; - no-indent-read is either a version of curly-infix-read, or a version
; of neoteric-read; this specal version accepts only a fake port.
; It is never a version of sweet-read. You don't normally want to
; call sweet-read, because sweet-read presumes that it's starting
; at the beginning of the line, with indentation processing still
; active. There's no reason either must be true when processing "#".
; - At the start of this procedure, both the # and the character
; after it have been read in.
; - The procedure returns one of the following:
; #f - the hash-character combination is invalid/not supported.
; (normal value) - the datum has value "value".
; (scomment ()) - the hash-character combination introduced a comment;
; at the return of this procedure with this value, the
; comment has been removed from the input port.
; You can use scomment-result, which has this value.
; (datum-commentw ()) - #; followed by whitespace.
; (abbrev value) - this is an abbreviation for value "value"
;
; hash-pipe-comment-nests?
; - a Boolean value that specifies whether #|...|# comments
; should nest.
;
; my-string-foldcase
; - a procedure to perform case-folding to lowercase, as mandated
; by Unicode. If your implementation doesn't have Unicode, define
; this to be string-downcase. Some implementations may also
; interpret "string-downcase" as foldcase anyway.
; On Guile 2.0, the define-module part needs to occur separately from
; the rest of the compatibility checks, unfortunately. Sigh.
(cond-expand
(guile
; define the module
; this ensures that the user's module does not get contaminated with
; our compatibility procedures/macros
(define-module (readable kernel))))
(cond-expand
; -----------------------------------------------------------------------------
; Guile Compatibility
; -----------------------------------------------------------------------------
(guile
; properly get bindings
(use-modules (guile))
; On Guile 1.x defmacro is the only thing supported out-of-the-box.
; This form still exists in Guile 2.x, fortunately.
(defmacro readable-kernel-module-contents (exports . body)
`(begin (export ,@exports)
,@body))
; Enable R5RS hygenic macro system (define-syntax) - guile 1.X
; does not automatically provide it, but version 1.6+ enable it this way
(use-syntax (ice-9 syncase))
; Guile was the original development environment, so the algorithm
; practically acts as if it is in Guile.
; Needs to be lambdas because otherwise Guile 2.0 acts strangely,
; getting confused on the distinction between compile-time,
; load-time and run-time (apparently, peek-char is not bound
; during load-time).
(define (my-peek-char fake-port)
(if (eof-object? (car fake-port))
(car fake-port)
(let* ((port (car fake-port))
(char (peek-char port)))
(if (eof-object? char)
(set-car! fake-port char))
char)))
(define (my-read-char fake-port)
(if (eof-object? (car fake-port))
(car fake-port)
(let* ((port (car fake-port))
(char (read-char port)))
(if (eof-object? char)
(set-car! fake-port char))
char)))
(define (make-read f)
(lambda args
(let ((port (if (null? args) (current-input-port) (car args))))
(f (list port)))))
(define (invoke-read read fake-port)
(if (eof-object? (car fake-port))
(car fake-port)
(read (car fake-port))))
; create a list with the source information
(define (get-sourceinfo fake-port)
(if (eof-object? (car fake-port))
#f
(let ((port (car fake-port)))
(list (port-filename port)
(port-line port)
(port-column port)))))
; destruct the list and attach, but only to cons cells, since
; only that is reliably supported across Guile versions.
(define (attach-sourceinfo pos obj)
(cond
((not pos)
obj)
((pair? obj)
(set-source-property! obj 'filename (list-ref pos 0))
(set-source-property! obj 'line (list-ref pos 1))
(set-source-property! obj 'column (list-ref pos 2))
obj)
(#t
obj)))
; To properly hack into 'load and in particular 'use-modules,
; we need to hack into 'primitive-load. On 1.8 and 2.0 there
; is supposed to be a current-reader fluid that primitive-load
; hooks into, but it seems (unverified) that each use-modules
; creates a new fluid environment, so that this only sticks
; on a per-module basis. But if the project is primarily in
; sweet-expressions, we would prefer to have that hook in
; *all* 'use-modules calls. So our primitive-load uses the
; 'read global variable if current-reader isn't set.
(define %sugar-current-load-port #f)
; replace primitive-load
(define primitive-load-replaced #f)
(define (setup-primitive-load)
(cond
(primitive-load-replaced
(values))
(#t
(module-set! (resolve-module '(guile)) 'primitive-load
(lambda (filename)
(let ((hook (cond
((not %load-hook)
#f)
((not (procedure? %load-hook))
(error "%load-hook must be procedure or #f"))
(#t
%load-hook))))
(cond
(hook
(hook filename)))
(let* ((port (open-input-file filename))
(save-port port))
(define (load-loop)
(let* ((the-read
(or
; current-reader doesn't exist on 1.6
(if (string=? "1.6" (effective-version))
#f
(fluid-ref current-reader))
read))
(form (the-read port)))
(cond
((not (eof-object? form))
; in Guile only
(primitive-eval form)
(load-loop)))))
(define (swap-ports)
(let ((tmp %sugar-current-load-port))
(set! %sugar-current-load-port save-port)
(set! save-port tmp)))
(dynamic-wind swap-ports load-loop swap-ports)
(close-input-port port)))))
(set! primitive-load-replaced #t))))
(define (replace-read-with f)
(setup-primitive-load)
(set! read f))
; Below implements some guile extensions, basically as guile 2.0.
; On Guile, #:x is a keyword. Keywords have symbol syntax.
; On Guile 1.6 and 1.8 the only comments are ; and #!..!#, but
; we'll allow more.
; On Guile 2.0, #; (SRFI-62) and #| #| |# |# (SRFI-30) comments exist.
; On Guile 2.0, #' #` #, #,@ have the R6RS meaning; on older
; Guile 1.8 and 1.6 there is a #' syntax but we have yet
; to figure out what exactly they do, and since those are becoming
; obsolete, we'll just use the R6RS meaning.
(define (parse-hash no-indent-read char fake-port)
; (let* ((ver (effective-version))
; (c (string-ref ver 0))
; (>=2 (and (not (char=? c #\0)) (not (char=? c #\1))))) ...)
(cond
((char=? char #\:)
; On Guile 1.6, #: reads characters until it finds non-symbol
; characters.
; On Guile 1.8 and 2.0, #: reads in a datum, and if the
; datum is not a symbol, throws an error.
; Follow the 1.8/2.0 behavior as it is simpler to implement,
; and even on 1.6 it is unlikely to cause problems.
; NOTE: This behavior means that #:foo(bar) will cause
; problems on neoteric and higher tiers.
(let ((s (no-indent-read fake-port)))
(if (symbol? s)
`(normal ,(symbol->keyword s) )
#f)))
; On Guile 2.0 #' #` #, #,@ have the R6RS meaning, handled in generics.
; Guile 1.6 and 1.8 have different meanings, but we'll ignore that.
; Guile's #{ }# syntax
((char=? char #\{ ) ; Special symbol, through till ...}#
`(normal ,(list->symbol (special-symbol fake-port))))
(#t #f)))
; Return list of characters inside #{...}#, a guile extension.
; presume we've already read the sharp and initial open brace.
; On eof we just end. We could error out instead.
; TODO: actually conform to Guile's syntax. Note that 1.x
; and 2.0 have different syntax when spaces, backslashes, and
; control characters get involved.
(define (special-symbol port)
(cond
((eof-object? (my-peek-char port)) '())
((eqv? (my-peek-char port) #\})
(my-read-char port) ; consume closing brace
(cond
((eof-object? (my-peek-char port)) '(#\}))
((eqv? (my-peek-char port) #\#)
(my-read-char port) ; Consume closing sharp.
'())
(#t (append '(#\}) (special-symbol port)))))
(#t (append (list (my-read-char port)) (special-symbol port)))))
(define hash-pipe-comment-nests? #t)
(define (my-string-foldcase s)
(string-downcase s))
; Here's how to import SRFI-69 in guile (for hash tables);
; we have to invoke weird magic becuase guile will
; complain about merely importing a normal SRFI like this
; (which I think is a big mistake, but can't fix guile 1.8):
; WARNING: (guile-user): imported module (srfi srfi-69)
; overrides core binding `make-hash-table'
; WARNING: (guile-user): imported module (srfi srfi-69)
; overrides core binding `hash-table?'
(use-modules ((srfi srfi-69)
#:select ((make-hash-table . srfi-69-make-hash-table)
(hash-table? . srfi-69-hash-table?)
hash-table-set!
hash-table-update!/default
hash-table-ref
hash-table-ref/default
hash-table-walk
hash-table-delete! )))
; For "any"
(use-modules (srfi srfi-1))
; There's no portable way to walk through other collections like records.
; Chibi has a "type" "type" procedure but isn't portable
; (and it's not in guile 1.8 at least).
; We'll leave it in, but stub it out; you can replace this with
; what your Scheme supports. Perhaps the "large" R7RS can add support
; for walking through arbitrary collections.
(define (type-of x) #f)
(define (type? x) #f)
)
; -----------------------------------------------------------------------------
; R5RS Compatibility
; -----------------------------------------------------------------------------
(else
; assume R5RS with define-syntax
; On R6RS, and other Scheme's, module contents must
; be entirely inside a top-level module structure.
; Use module-contents to support that. On Schemes
; where module declarations are separate top-level
; expressions, we expect module-contents to transform
; to a simple (begin ...), and possibly include
; whatever declares exported stuff on that Scheme.
(define-syntax readable-kernel-module-contents
(syntax-rules ()
((readable-kernel-module-contents exports body ...)
(begin body ...))))
; We use my-* procedures so that the
; "port" automatically keeps track of source position.
; On Schemes where that is not true (e.g. Racket, where
; source information is passed into a reader and the
; reader is supposed to update it by itself) we can wrap
; the port with the source information, and update that
; source information in the my-* procedures.
(define (my-peek-char port) (peek-char port))
(define (my-read-char port) (read-char port))
; this wrapper procedure wraps a reader procedure
; that accepts a "fake" port above, and converts
; it to an R5RS-compatible procedure. On Schemes
; which support source-information annotation,
; but use a different way of annotating
; source-information from Guile, this procedure
; should also probably perform that attachment
; on exit from the given inner procedure.
(define (make-read f)
(lambda args
(let ((real-port (if (null? args) (current-input-port) (car args))))
(f real-port))))
; invoke the given "actual" reader, most likely
; the builtin one, but make sure to unwrap any
; fake ports.
(define (invoke-read read port)
(read port))
; R5RS doesn't have any method of extracting
; or attaching source location information.
(define (get-sourceinfo _) #f)
(define (attach-sourceinfo _ x) x)
; Not strictly R5RS but we expect at least some Schemes
; to allow this somehow.
(define (replace-read-with f)
(set! read f))
; R5RS has no hash extensions
(define (parse-hash no-indent-read char fake-port) #f)
; Hash-pipe comment is not in R5RS, but support
; it as an extension, and make them nest.
(define hash-pipe-comment-nests? #t)
; If your Scheme supports "string-foldcase", use that instead of
; string-downcase:
(define (my-string-foldcase s)
(string-downcase s))
; Somehow get SRFI-69 and SRFI-1
))
; -----------------------------------------------------------------------------
; Module declaration and useful utilities
; -----------------------------------------------------------------------------
(readable-kernel-module-contents
; exported procedures
(; tier read procedures
curly-infix-read neoteric-read sweet-read
; set read mode
set-read-mode
; replacing the reader
replace-read restore-traditional-read
enable-curly-infix enable-neoteric enable-sweet
; Various writers.
curly-write-simple neoteric-write-simple
curly-write curly-write-cyclic curly-write-shared
neoteric-write neoteric-write-cyclic neoteric-write-shared)
; Should we fold case of symbols by default?
; #f means case-sensitive (R6RS); #t means case-insensitive (R5RS).
; Here we'll set it to be case-sensitive, which is consistent with R6RS
; and guile, but NOT with R5RS. Most people won't notice, I
; _like_ case-sensitivity, and the latest spec is case-sensitive,
; so let's start with #f (case-sensitive).
; This doesn't affect character names; as an extension,
; We always accept arbitrary case for them, e.g., #\newline or #\NEWLINE.
(define is-foldcase #f)
; special tag to denote comment return from hash-processing
; Define the whitespace characters, in relatively portable ways
; Presumes ASCII, Latin-1, Unicode or similar.
(define tab (integer->char #x0009)) ; #\ht aka \t.
(define linefeed (integer->char #x000A)) ; #\newline aka \n. FORCE it.
(define carriage-return (integer->char #x000D)) ; \r.
(define line-tab (integer->char #x000D))
(define form-feed (integer->char #x000C))
(define vertical-tab (integer->char #x000b))
(define space '#\space)
; Period symbol. A symbol starting with "." is not
; validly readable in R5RS, R6RS, R7RS (except for
; the peculiar identifier "..."); with the
; R6RS and R7RS the print representation of
; string->symbol(".") should be |.| . However, as an extension, this
; Scheme reader accepts "." as a valid identifier initial character,
; in part because guile permits it.
; For portability, use this formulation instead of '. in this
; implementation so other implementations don't balk at it.
(define period-symbol (string->symbol "."))
(define line-ending-chars (list linefeed carriage-return))
; This definition of whitespace chars is derived from R6RS section 4.2.1.
; R6RS doesn't explicitly list the #\space character, be sure to include!
(define whitespace-chars-ascii
(list tab linefeed line-tab form-feed carriage-return #\space))
; Note that we are NOT trying to support all Unicode whitespace chars.
(define whitespace-chars whitespace-chars-ascii)
; If #t, handle some constructs so we can read and print as Common Lisp.
(define common-lisp #f)
; If #t, return |...| symbols as-is, including the vertical bars.
(define literal-barred-symbol #f)
; Returns a true value (not necessarily #t)
(define (char-line-ending? char) (memv char line-ending-chars))
; Create own version, in case underlying implementation omits some.
(define (my-char-whitespace? c)
(or (char-whitespace? c) (memv c whitespace-chars)))
; Consume an end-of-line sequence, ('\r' '\n'? | '\n'), and nothing else.
; Don't try to handle reversed \n\r (LFCR); doing so will make interactive
; guile use annoying (EOF won't be correctly detected) due to a guile bug
; (in guile before version 2.0.8, peek-char incorrectly
; *consumes* EOF instead of just peeking).
(define (consume-end-of-line port)
(let ((c (my-peek-char port)))
(cond
((eqv? c carriage-return)
(my-read-char port)
(if (eqv? (my-peek-char port) linefeed)
(my-read-char port)))
((eqv? c linefeed)
(my-read-char port)))))
(define (consume-to-eol port)
; Consume every non-eol character in the current line.
; End on EOF or end-of-line char.
; Do NOT consume the end-of-line character(s).
(let ((c (my-peek-char port)))
(cond
((and (not (eof-object? c)) (not (char-line-ending? c)))
(my-read-char port)
(consume-to-eol port)))))
(define (consume-to-whitespace port)
; Consume to whitespace
(let ((c (my-peek-char port)))
(cond
((eof-object? c) c)
((my-char-whitespace? c)
'())
(#t
(my-read-char port)
(consume-to-whitespace port)))))
(define debugger-output #f)
; Quick utility for debugging. Display marker, show data, return data.
(define (debug-show marker data)
(cond
(debugger-output
(display "DEBUG: ")
(display marker)
(display " = ")
(write data)
(display "\n")))
data)
(define (my-read-delimited-list my-read stop-char port)
; Read the "inside" of a list until its matching stop-char, returning list.
; stop-char needs to be closing paren, closing bracket, or closing brace.
; This is like read-delimited-list of Common Lisp, but it
; calls the specified reader instead.
; This implements a useful extension: (. b) returns b. This is
; important as an escape for indented expressions, e.g., (. \\)
(consume-whitespace port)
(let*
((pos (get-sourceinfo port))
(c (my-peek-char port)))
(cond
((eof-object? c) (read-error "EOF in middle of list") c)
((char=? c stop-char)
(my-read-char port)
(attach-sourceinfo pos '()))
((memv c '(#\) #\] #\})) (read-error "Bad closing character") c)
(#t
(let ((datum (my-read port)))
(cond
((and (eq? datum period-symbol) (char=? c #\.))
(let ((datum2 (my-read port)))
(consume-whitespace port)
(cond
((eof-object? datum2)
(read-error "Early eof in (... .)")
'())
((not (eqv? (my-peek-char port) stop-char))
(read-error "Bad closing character after . datum")
datum2)
(#t
(my-read-char port)
datum2))))
(#t
(attach-sourceinfo pos
(cons datum
(my-read-delimited-list my-read stop-char port))))))))))
; -----------------------------------------------------------------------------
; Read preservation, replacement, and mode setting
; -----------------------------------------------------------------------------
(define default-scheme-read read)
(define replace-read replace-read-with)
(define (restore-traditional-read) (replace-read-with default-scheme-read))
(define (enable-curly-infix)
(if (not (or (eq? read curly-infix-read)
(eq? read neoteric-read)
(eq? read sweet-read)))
(replace-read curly-infix-read)))
(define (enable-neoteric)
(if (not (or (eq? read neoteric-read)
(eq? read sweet-read)))
(replace-read neoteric-read)))
(define (enable-sweet)
(replace-read sweet-read))
(define current-read-mode #f)
(define (set-read-mode mode port)
; TODO: Should be per-port
(cond
((eq? mode 'common-lisp)
(set! common-lisp #t) #t)
((eq? mode 'literal-barred-symbol)
(set! literal-barred-symbol #t) #t)
((eq? mode 'fold-case)
(set! is-foldcase #t) #t)
((eq? mode 'no-fold-case)
(set! is-foldcase #f) #t)
(#t (display "Warning: Unknown mode") #f)))
; -----------------------------------------------------------------------------
; Scheme Reader re-implementation
; -----------------------------------------------------------------------------
; We have to re-implement our own Scheme reader.
; This takes more code than it would otherwise because many
; Scheme readers will not consider [, ], {, and } as delimiters
; (they are not required delimiters in R5RS and R6RS).
; Thus, we cannot call down to the underlying reader to implement reading
; many types of values such as symbols.
; If your Scheme's "read" also considers [, ], {, and } as
; delimiters (and thus are not consumed when reading symbols, numbers, etc.),
; then underlying-read could be much simpler.
; We WILL call default-scheme-read on string reading (the ending delimiter
; is ", so that is no problem) - this lets us use the implementation's
; string extensions if any.
; Identifying the list of delimiter characters is harder than you'd think.
; This list is based on R6RS section 4.2.1, while adding [] and {},
; but removing "#" from the delimiter set.
; NOTE: R6RS has "#" has a delimiter. However, R5RS does not, and
; R7RS probably will not - http://trac.sacrideo.us/wg/wiki/WG1Ballot3Results
; shows a strong vote AGAINST "#" being a delimiter.
; Having the "#" as a delimiter means that you cannot have "#" embedded
; in a symbol name, which hurts backwards compatibility, and it also
; breaks implementations like Chicken (has many such identifiers) and
; Gambit (which uses this as a namespace separator).
; Thus, this list does NOT have "#" as a delimiter, contravening R6RS
; (but consistent with R5RS, probably R7RS, and several implementations).
; Also - R7RS draft 6 has "|" as delimiter, but we currently don't.
(define neoteric-delimiters
(append (list #\( #\) #\[ #\] #\{ #\} ; Add [] {}
#\" #\;) ; Could add #\# or #\|
whitespace-chars))
(define (consume-whitespace port)
(let ((char (my-peek-char port)))
(cond
((eof-object? char))
((eqv? char #\;)
(consume-to-eol port)
(consume-whitespace port))
((my-char-whitespace? char)
(my-read-char port)
(consume-whitespace port)))))
(define (read-until-delim port delims)
; Read characters until eof or a character in "delims" is seen.
; Do not consume the eof or delimiter.
; Returns the list of chars that were read.
(let ((c (my-peek-char port)))
(cond
((eof-object? c) '())
((memv c delims) '())
(#t (my-read-char port) (cons c (read-until-delim port delims))))))
(define (read-error message)
(display "Error: " (current-error-port))
(display message (current-error-port))
(newline (current-error-port))
; Guile extension to flush output on stderr
(force-output (current-error-port))
; Guile extension, but many Schemes have exceptions
(throw 'readable)
'())
; Return the number by reading from port, and prepending starting-lyst.
; Returns #f if it's not a number.
(define (read-number port starting-lyst)
(string->number (list->string
(append starting-lyst
(read-until-delim port neoteric-delimiters)))))
; Return list of digits read from port; may be empty.
(define (read-digits port)
(let ((c (my-peek-char port)))
(cond
((memv c digits)
(cons (my-read-char port) (read-digits port)))
(#t '()))))
(define char-name-values
; Includes standard names and guile extensions; see
; http://www.gnu.org/software/guile/manual/html_node/Characters.html
'((space #x0020)
(newline #x000a)
(nl #x000a)
(tab #x0009)
(nul #x0000)
(null #x0000)
(alarm #x0007)
(backspace #x0008)
(linefeed #x000a)
(vtab #x000b)
(page #x000c)
(return #x000d)
(esc #x001b)
(delete #x007f)
; Additional character names as extensions:
(soh #x0001)
(stx #x0002)
(etx #x0003)
(eot #x0004)
(enq #x0005)
(ack #x0006)
(bel #x0007)
(bs #x0008)
(ht #x0009)
(lf #x000a)
(vt #x000b)
(ff #x000c)
(np #x000c) ; new page
(cr #x000d)
(so #x000e)
(si #x000f)
(dle #x0010)
(dc1 #x0011)
(dc2 #x0012)
(dc3 #x0013)
(dc4 #x0014)
(nak #x0015)
(syn #x0016)
(etb #x0017)
(can #x0018)
(em #x0019)
(sub #x001a)
(fs #x001c)
(gs #x001d)
(rs #x001e)
(sp #x0020)
(del #x007f)
; Other non-guile names.
; rubout noted in: http://docs.racket-lang.org/reference/characters.html
; It's also required by the Common Lisp spec.
(rubout #x007f)))
(define (process-char port)
; We've read #\ - returns what it represents.
(cond
((eof-object? (my-peek-char port)) (my-peek-char port))
(#t
; Not EOF. Read in the next character, and start acting on it.
(let ((c (my-read-char port))
(rest (read-until-delim port neoteric-delimiters)))
(cond
((null? rest) c) ; only one char after #\ - so that's it!
(#t ; More than one char; do a lookup.
(let* ((cname (string->symbol
(string-downcase (list->string (cons c rest)))))
(found (assq cname char-name-values)))
(if found
(integer->char (cadr found))
(read-error "Invalid character name")))))))))
; If fold-case is active on this port, return string "s" in folded case.
; Otherwise, just return "s". This is needed to support our
; is-foldcase configuration value when processing symbols.
; TODO: Should be port-specific
(define (fold-case-maybe port s)
(if is-foldcase
(my-string-foldcase s)
s))
(define (process-directive dir)
(cond
; TODO: These should be specific to the port.
((string-ci=? dir "sweet")
(enable-sweet))
((string-ci=? dir "no-sweet")
(restore-traditional-read))
((string-ci=? dir "curly-infix")
(replace-read curly-infix-read))
((string-ci=? dir "fold-case")
(set! is-foldcase #t))
((string-ci=? dir "no-fold-case")
(set! is-foldcase #f))
(#t (display "Warning: Unknown process directive"))))
; Consume characters until "!#"
(define (non-nest-comment port)
(let ((c (my-read-char port)))
(cond
((eof-object? c)
(values))
((char=? c #\!)
(let ((c2 (my-peek-char port)))
(if (char=? c2 #\#)
(begin
(my-read-char port)
(values))
(non-nest-comment port))))
(#t
(non-nest-comment port)))))
(define (process-sharp-bang port)
(let ((c (my-peek-char port)))
(cond
((char=? c #\space) ; SRFI-22
(consume-to-eol port)
(consume-end-of-line port)
scomment-result) ; Treat as comment.
((memv c '(#\/ #\.)) ; Multi-line, non-nesting #!/ ... !# or #!. ...!#
(non-nest-comment port)
scomment-result) ; Treat as comment.
((char-alphabetic? c) ; #!directive
(process-directive
(list->string (read-until-delim port neoteric-delimiters)))
scomment-result)
((or (eqv? c carriage-return) (eqv? c #\newline))
; Extension: Ignore lone #!
(consume-to-eol port)
(consume-end-of-line port)
scomment-result) ; Treat as comment.
(#t (read-error "Unsupported #! combination")))))
; A cons cell always has a unique address (as determined by eq?);
; we'll use this special cell to tag unmatched datum label references.
; An unmatched datum label will have the form
; (cons unmatched-datum-label-tag NUMBER)
(define unmatched-datum-label-tag
(cons 'unmatched-datum-label-tag 'label))
(define (is-matching-label-tag? number value)
(and
(pair? value)
(eq? (car value) unmatched-datum-label-tag)
(eqv? (cdr value) number)))
; Patch up datum, starting at position,
; so that all labels "number" are replaced
; with the value of "replace".
; Note that this actually OVERWRITES PORTIONS OF A LIST with "set!",
; so that we can maintain "eq?"-ness. This is really wonky,
; but datum labels are themselves wonky.
; "skip" is a list of locations that don't need (re)processing; it
; should be a hash table but those aren't portable.
(define (patch-datum-label-tail number replace position skip)
(let ((new-skip (cons position skip)))
(cond
((and (pair? position)
(not (eq? (car position) unmatched-datum-label-tag))
(not (memq position skip)))
(if (is-matching-label-tag? number (car position))
(set-car! position replace) ; Yes, "set!" !!
(patch-datum-label-tail number replace (car position) new-skip))
(if (is-matching-label-tag? number (cdr position))
(set-cdr! position replace) ; Yes, "set!" !!
(patch-datum-label-tail number replace (cdr position) new-skip)))
((vector? position)
(do ((len (vector-length position))
(k 0 (+ k 1)))
((>= k len) (values))
(let ((x (vector-ref position k)))
(if (is-matching-label-tag? number x)
(vector-set! position k replace)
(patch-datum-label-tail number replace x new-skip)))))
(#t (values)))))
(define (patch-datum-label number starting-position)
(if (is-matching-label-tag? number starting-position)
(read-error "Illegal reference as the labelled object itself"))
(patch-datum-label-tail number starting-position starting-position '())
starting-position)
; Gobble up the to-gobble characters from port, and return # ungobbled.
(define (gobble-chars port to-gobble)
(if (null? to-gobble)
0
(cond
((char-ci=? (my-peek-char port) (car to-gobble))
(my-read-char port)
(gobble-chars port (cdr to-gobble)))
(#t (length to-gobble)))))
(define scomment-result '(scomment ()))
(define (process-sharp no-indent-read port)
; We've read a # character. Returns what it represents as
; (stopper value); ('normal value) is value, ('scomment ()) is comment.
; Since we have to re-implement process-sharp anyway,
; the vector representation #(...) uses my-read-delimited-list, which in
; turn calls no-indent-read.
; TODO: Create a readtable for this case.
(let ((c (my-peek-char port)))
(cond
((eof-object? c) scomment-result) ; If eof, pretend it's a comment.
((char-line-ending? c) ; Extension - treat # EOL as a comment.
scomment-result) ; Note this does NOT consume the EOL!
(#t ; Try out different readers until we find a match.
(my-read-char port)
(or
(and common-lisp
(parse-cl no-indent-read c port))
(parse-hash no-indent-read c port)
(parse-default no-indent-read c port)
(read-error "Invalid #-prefixed string"))))))
(define (parse-default no-indent-read c port)
(cond ; Nothing special - use generic rules
((char-ci=? c #\t)
(if (memv (gobble-chars port '(#\r #\u #\e)) '(0 3))
'(normal #t)
(read-error "Incomplete #true")))
((char-ci=? c #\f)
(if (memv (gobble-chars port '(#\a #\l #\s #\e)) '(0 4))
'(normal #f)
(read-error "Incomplete #false")))
((memv c '(#\i #\e #\b #\o #\d #\x
#\I #\E #\B #\O #\D #\X))
(let ((num (read-number port (list #\# (char-downcase c)))))
(if num
`(normal ,num)
(read-error "Not a number after number start"))))
((char=? c #\( ) ; Vector.
(list 'normal (list->vector
(my-read-delimited-list no-indent-read #\) port))))
((char=? c #\u ) ; u8 Vector.
(cond
((not (eqv? (my-read-char port) #\8 ))
(read-error "#u must be followed by 8"))
((not (eqv? (my-read-char port) #\( ))
(read-error "#u8 must be followed by left paren"))
(#t (list 'normal (list->u8vector
(my-read-delimited-list no-indent-read #\) port))))))
((char=? c #\\)
(list 'normal (process-char port)))
; Handle #; (item comment).
((char=? c #\;)