forked from mighty-gerbils/gerbil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.ss
3179 lines (2925 loc) · 113 KB
/
core.ss
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
;;; -*- Gerbil -*-
;;; (C) vyzo at hackzen.org
;;; :gerbil/core prelude
prelude: :<root>
package: gerbil
(export #t
(import: <runtime> <sugar> <MOP> <match> <more-sugar>
<module-sugar>)
(phi: +1 (import: <runtime> <sugar> <MOP> <match> <more-sugar>
<expander-runtime> <syntax-case> <syntax-sugar>
<more-syntax-sugar>)))
(provide gerbil-core)
;;;
;;; r5rs procedures
;;;
(module <r5rs-runtime>
(export #t)
(extern namespace: #f
;; 6.1 equivalnce
eq? eqv? equal?
;; 6.2 numbers
number? complex? real? rational? integer?
exact? inexact?
= < > <= >=
zero? positive? negative? odd? even?
max min
+ * - /
abs quotient remainder modulo gcd lcm
floor ceiling truncate round
numerator denominator rationalize
exp log sin cos tan asin acos atan
sqrt expt
make-rectangular make-polar real-part imag-part magnitude angle
exact->inexact inexact->exact
number->string string->number
;; 6.3 other data types
;; 6.3.1 bool
not boolean?
;; 6.3.2 pairs
pair? cons car cdr set-car! set-cdr!
caar cadr cdar cddr
caaar cadar caadr caddr
cdaar cddar cdadr cdddr
caaaar caadar caaadr caaddr
cadaar caddar cadadr cadddr
cdaaar cdadar cdaadr cdaddr
cddaar cdddar cddadr cddddr
null? list? list length append reverse list-tail list-ref
memq memv member
assq assv assoc
;; 6.3.3 symbols
symbol? symbol->string string->symbol
;; 6.3.4 characters
char? char=? char<? char>? char<=? char>=?
char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=?
char-alphabetic? char-numeric? char-whitespace?
char-upper-case? char-lower-case?
char->integer integer->char
char-upcase char-downcase
;; 6.3.5 strings
string? make-string string
string-length string-ref string-set!
string=? string-ci=?
string<? string>? string<=? string>=?
string-ci<? string-ci>? string-ci<=? string-ci>=?
substring string-append
string->list list->string
string-copy string-fill!
;; 6.3.6 vectors
vector? make-vector vector
vector-length vector-ref vector-set!
vector->list list->vector
vector-fill!
;; 6.4 control
procedure? apply
map for-each
force
call-with-current-continuation
call-with-values values
dynamic-wind
;; 6.5 eval
eval interaction-environment scheme-report-environment
;; 6.6 i/o
call-with-input-file call-with-output-file
input-port? output-port?
current-input-port current-output-port
with-input-from-file with-output-to-file
open-input-file open-output-file
close-input-port close-output-port
read read-char peek-char
eof-object? char-ready?
write display newline write-char
load
;; transcript-on transcript-off ; void
))
;;;
;;; Common Runtime
;;;
(module <host-runtime>
(export #t)
(extern namespace: #f
immediate?
finite? infinite? nan?
1+ 1- fx+ fx1+ fx- fx1- fx* fx/
fixnum? nonnegative-fixnum?
fxzero? fxpositive? fxnegative? fxodd? fxeven?
fixnum->char char->fixnum fixnum->flonum
fxmax fxmin fxabs fxnot fxand fxior fxxor fxand fxmodulo
fxbit-set? fxarithmetic-shift fxshift
fx< fx<= fx= fx>= fx>
flonum?
fl+ fl- fl* fl/ fl< fl<= fl= fl>= fl>
flzero? flpositive? flnegative?
flnan? flinfinite? flfinite? flinteger?
flmax flmin
box? box unbox set-box!
make-list cons*
foldl foldr andmap ormap filter filter-map iota last last-pair
memf assgetq assgetv assget find
remove remq remv remf
pgetq pgetv pget
subvector subvector->list subvector-fill!
vector-map vector-copy vector-append
true true? false void void? eof-object identity
dssl-object? dssl-key-object? dssl-rest-object? dssl-optional-object?
values-count values->list
make-hash-table make-hash-table-eq make-hash-table-eqv
hash-table?
hash->list hash->plist
list->hash-table list->hash-table-eq list->hash-table-eqv
plist->hash-table plist->hash-table-eq plist->hash-table-eqv
hash-length hash-ref hash-get hash-put! hash-remove! hash-update! hash-key?
hash-find hash-for-each hash-map hash-fold
hash-keys hash-values
hash-copy hash-copy!
hash-merge hash-merge!
eq?-hash eqv?-hash equal?-hash
uninterned-symbol? interned-symbol?
gensym make-symbol make-uninterned-symbol symbol-hash
keyword? uninterned-keyword? interned-keyword? keyword-hash
string->bytes substring->bytes bytes->string
string->keyword keyword->string make-uninterned-keyword
symbol->keyword keyword->symbol
substring-fill! substring-move! string-shrink!
append-strings
string-map string-index string-rindex
string-split string-join string-empty? string-prefix?
;; MOP
type-descriptor?
struct-type?
class-type?
make-struct-type
make-struct-predicate
make-struct-field-accessor
make-struct-field-mutator
make-struct-field-unchecked-accessor
make-struct-field-unchecked-mutator
struct-field-ref
struct-field-set!
unchecked-field-ref
unchecked-field-set!
make-class-type
make-class-predicate
make-class-slot-accessor
make-class-slot-mutator
make-class-slot-unchecked-accessor
make-class-slot-unchecked-mutator
class-slot-ref
class-slot-set!
unchecked-slot-ref
unchecked-slot-set!
object? object-type
struct-instance? class-instance?
direct-struct-instance? direct-class-instance?
make-object
struct->list class->list
make-struct-instance
make-class-instance
struct-instance-init!
class-instance-init!
constructor-init!
slot-ref slot-set!
call-method
bind-method!
method-ref direct-method-ref bound-method-ref
checked-method-ref checked-bound-method-ref
find-method
next-method call-next-method
struct-subtype? class-subtype?
;; control
current-error-port
make-promise promise?
make-parameter call-with-parameters
call-with-escape
;;call-with-prompt abort!
with-unwind-protect
current-exception-handler with-exception-handler
with-catch
error raise raise-type-error
exception? error-object? type-error?
exception::t error::t
error? error-trace error-message error-irritants
;; OS
exit getenv setenv
current-directory create-directory create-directory*
delete-file copy-file rename-file
delete-directory directory-files
file-exists? file-newer? file-type
path-expand path-normalize
path-extension path-strip-extension
path-directory path-strip-directory
path-strip-trailing-directory-separator
;; reader
AST::t AST? AST-e AST-source make-AST
read-syntax read-syntax-from-file
source-location? source-location-path? source-location-path
;; required by the module reader to support #lang
datum-parsing-exception? datum-parsing-exception-filepos
read-line read-all
;; string and vector moves
append-vectors subvector-move! vector-shrink!
append-strings substring-move! string-shrink!
;; string I/O
write-substring
open-input-string open-output-string get-output-string
call-with-input-string with-input-from-string
call-with-output-string with-output-to-string
;; bytes
u8vector? u8vector
make-u8vector u8vector-length u8vector-ref u8vector-set!
u8vector->list list->u8vector
u8vector-fill! u8vector-shrink!
u8vector-copy u8vector-append
subu8vector subu8vector-fill! subu8vector-move!
append-u8vectors
object->u8vector u8vector->object
;; bytes I/O
write-subu8vector
open-input-u8vector open-output-u8vector get-output-u8vector
call-with-input-u8vector with-input-from-u8vector
call-with-output-u8vector with-output-to-u8vector
;; generic I/O
displayln display*
;;flush-output-port
;; etc...
absent-obj ; gambit api missing optional parameter
absent-value ; unbound hash reference atom
;; Module loading
load-module
;; keyword argument dispatch
keyword-dispatch
;; gerbil specifics
gerbil-version-string gerbil-system-version-string
;; system type information
gerbil-system system-type
;; voodoo doll
gerbil-runtime-smp?
)
(define-alias transcript-on void)
(define-alias transcript-off void)
(define-alias car-set! set-car!)
(define-alias cdr-set! set-cdr!)
(define-alias box-set! set-box!)
(define-alias call/cc call-with-current-continuation)
(define-alias call/esc call-with-escape)
(define-alias call/values call-with-values)
(define-alias call/parameters call-with-parameters)
;;(define-alias call/prompt call-with-prompt)
)
(module <runtime>
(import <r5rs-runtime> <host-runtime>)
(export (import: <r5rs-runtime> <host-runtime>)))
(module <expander-runtime>
(export #t)
(extern namespace: gx
;; syntax and friends
raise-syntax-error syntax-error?
identifier? identifier-list? free-identifier=? bound-identifier=?
datum->syntax syntax->datum syntax-e syntax->list
genident gentemps
stx-identifier
stx-boolean? stx-keyword? stx-char? stx-number? stx-fixnum? stx-string?
stx-null? stx-pair? stx-pair/null? stx-list?
stx-box? stx-vector? stx-datum?
stx-eq? stx-eqv? stx-equal? stx-false?
stx-e stx-source stx-wrap-source
stx-car stx-cdr stx-length
stx-for-each stx-map stx-foldl stx-foldr stx-reverse
stx-last stx-last-pair stx-list-tail stx-list-ref
stx-andmap stx-ormap
stx-plist? stx-getq
macro-expand-syntax
macro-expand-syntax-case
syntax-pattern? syntax-local-pattern?
make-syntax-pattern syntax-pattern-id syntax-pattern-depth
syntax-check-splice-targets
syntax-split-splice
underscore? ellipsis?
check-duplicate-identifiers
;; core expander -- user api
current-expander-context
current-expander-marks
current-expander-path
current-expander-phi
current-module-reader-path
current-module-reader-args
local-context? top-context? module-context? prelude-context?
expander-context-id module-context-ns
make-local-context
eval-syntax core-expand core-expand-head core-expand-expression+1
import-module eval-module
core-library-module-path? core-resolve-library-module-path
core-resolve-module-path
core-quote-syntax
core-identifier=? core-identifier-key
core-apply-expander
syntax-local-introduce syntax-local-rewrap syntax-local-unwrap
syntax-local-e syntax-local-value
resolve-identifier core-resolve-identifier
binding? binding-id
runtime-binding? top-binding? module-binding? extern-binding?
syntax-binding? syntax-binding-e
alias-binding? alias-binding-e
import-binding? import-binding-e
expander? expander-binding? expander-e expander-binding-e
feature-expander?
user-expander? make-user-expander
user-expander-context user-expander-phi
import-expander? make-import-expander
export-expander? make-export-expander
import-export-expander? make-import-export-expander
module-import? make-module-import
module-import-source module-import-name module-import-phi
module-import-weak?
module-export? make-module-export
module-export-context module-export-key module-export-phi
module-export-name module-export-weak?
import-set? import-set-source import-set-phi import-set-imports
export-set? export-set-source export-set-phi export-set-exports
core-resolve-module-export
core-module-export->import
core-expand-import-source
core-expand-export-source))
(import <runtime>
(phi: +1 <runtime> <expander-runtime>)
(phi: +2 <runtime> <expander-runtime>)
(phi: +3 <runtime> <expander-runtime>))
(module <syntax-case>
(export #t)
(import <expander-runtime>) ; for template
(define-syntax syntax
macro-expand-syntax)
(define-syntax syntax-case
macro-expand-syntax-case))
(import (phi: +1 <syntax-case>)
(phi: +2 <syntax-case>))
(module <syntax-sugar>
(export #t)
(import <expander-runtime> <syntax-case>)
(define-syntax syntax-rules
(lambda% (stx)
(syntax-case stx ()
((_ ids clauses ...)
(identifier-list? #'ids)
(let-values (((body)
(stx-map
(lambda% (clause)
(syntax-case clause ()
((hd body)
#'(hd (syntax body)))
((hd fender body)
#'(hd fender (syntax body)))))
#'(clauses ...))))
(syntax-case body ()
((clause ...)
#'(lambda% ($stx)
(syntax-case $stx ids
clause ...)))))))))
(define-syntax with-syntax
(lambda% (stx)
(syntax-case stx ()
((_ () body ...)
#'(let-values () body ...))
((_ ((pat e)) body ...)
#'(syntax-case e ()
(pat (let-values () body ...))))
((_ ((pat e) ...) body ...)
#'(syntax-case (list e ...) ()
((pat ...) (let-values () body ...)))))))
(define-syntax with-syntax*
(lambda% (stx)
(syntax-case stx (values)
((_ () body ...)
#'(let-values () body ...))
((recur (((values . hd) e) . rest) body ...)
#'(let-values ((hd e))
(recur rest body ...)))
((recur (hd . rest) body ...)
#'(with-syntax (hd)
(recur rest body ...))))))
(define-syntax syntax/loc
(lambda% (stx)
(syntax-case stx ()
((_ src-stx form)
#'(stx-wrap-source
(syntax form)
(stx-source src-stx)))))))
(import (phi: +1 <syntax-sugar>)
(phi: +2 <syntax-sugar>))
(module <sugar>
(export (import: <sugar:1> <sugar:2> <sugar:3>))
(module <sugar:1>
(export #t)
(define-syntax defrules
(syntax-rules ()
((_ id kws clauses ...)
(identifier? #'id)
(define-syntax id
(syntax-rules kws clauses ...)))))
(define-alias define-rules defrules)
(defrules defsyntax% ()
((_ (id . args) body ...)
(identifier? #'id)
(define-syntax id
(lambda% args body ...)))
((_ id expr)
(identifier? #'id)
(define-syntax id expr)))
(defrules defalias ()
((_ id alias-id)
(define-alias id alias-id)))
(defrules define ()
((_ (id . args) body ...)
(identifier? #'id)
(define-values (id)
(lambda% args body ...)))
((_ id expr)
(identifier? #'id)
(define-values (id)
expr)))
(defrules let*-values ()
((_ () body ...)
(let-values () body ...))
((recur (hd . rest) body ...)
(let-values (hd)
(recur rest body ...))))
(defrules let ()
((_ id ((var arg) ... . rest) body ...)
(identifier? #'id)
((letrec-values (((id) (lambda% (var ... . rest) body ...)))
id)
arg ...))
((_ hd body ...)
(~let let-values hd body ...)))
(defrules let* ()
((_ hd body ...)
(~let let*-values hd body ...)))
(defrules letrec ()
((_ hd body ...)
(~let letrec-values hd body ...)))
(defrules letrec* ()
((_ hd body ...)
(~let letrec*-values hd body ...)))
(defsyntax% (~let stx)
(define-values (let-head?)
(lambda% (x)
(syntax-case x (values)
((values . ids)
(stx-andmap identifier? #'ids))
(_ (identifier? x)))))
(define-values (let-head)
(lambda% (x)
(syntax-case x (values)
((values . ids) #'ids)
(_ (list x)))))
(syntax-case stx ()
((recur form (hd e) . body)
(let-head? #'hd)
#'(recur form ((hd e)) . body))
((_ form ((hd e) ...) body ...)
(stx-andmap let-head? #'(hd ...))
(with-syntax (((hd-bind ...)
(stx-map let-head #'(hd ...))))
#'(form ((hd-bind e) ...) body ...)))))
(defrules and ()
((_) #t)
((_ x) x)
((recur x . rest)
(if x (recur . rest) #f)))
(defrules or ()
((_) #f)
((_ x) x)
((recur x . rest)
(let ($e x)
(if $e $e (recur . rest)))))
(defrules cond (else =>)
((_) #!void)
((_ (else body ...))
(%#expression (begin body ...)))
((_ (else . _) . _)
(syntax-error "Bad syntax; misplaced else"))
((recur (test => K) . rest)
(let ($e test)
(if $e (K $e) (recur . rest))))
((recur (test) . rest)
(recur (test => values) . rest))
((recur (test body ...) . rest)
(if test (begin body ...) (recur . rest))))
(defrules when ()
((_ test expr ...)
(if test (begin expr ...) #!void)))
(defrules unless ()
((_ test expr ...)
(if test #!void (begin expr ...))))
(defsyntax% (syntax-error stx)
(syntax-case stx ()
((_ message detail ...)
(stx-string? #'message)
(apply raise-syntax-error #f (stx-e #'message) stx
(syntax->list #'(detail ...)))))))
(import <sugar:1>
(phi: +1 <sugar:1>))
(module <sugar:2>
(export #t)
;; begin with lambda
(defsyntax% (lambda stx)
(define (simple-lambda? hd)
(stx-andmap identifier? hd))
(define (opt-lambda? hd)
(let lp ((rest hd) (opt? #f))
(syntax-case rest ()
((hd . hd-rest)
(syntax-case #'hd ()
((id _)
(identifier? #'id)
(lp #'hd-rest #t))
(_ (and (identifier? #'hd) (not opt?)
(lp #'hd-rest #f)))))
(_ (and opt? (or (stx-null? rest)
(identifier? rest)))))))
(define (opt-lambda-split hd)
(let lp ((rest hd) (pre '()) (opt '()))
(syntax-case rest ()
((hd . hd-rest)
(syntax-case #'hd ()
((id e)
(lp #'hd-rest pre
(cons (cons (generate-bind #'id) #'e)
opt)))
(_ (lp #'hd-rest
(cons (generate-bind #'hd)
pre)
opt))))
(_ (values (reverse pre)
(reverse opt)
(if (identifier? rest)
(generate-bind rest)
rest))))))
(define (kw-lambda? hd)
(let lp ((rest hd) (opt? #f) (key? #f))
(syntax-case rest ()
((key bind . hd-rest)
(stx-keyword? #'key)
(syntax-case #'bind ()
((id _)
(and (identifier? #'id)
(lp #'hd-rest opt? #t)))
(_ (and (identifier? #'bind)
(lp #'hd-rest opt? #t)))))
((#!key id . hd-rest)
(and (identifier? #'id)
(lp #'hd-rest opt? #t)))
((hd . hd-rest)
(syntax-case #'hd ()
((id _)
(and (identifier? #'id)
(lp #'hd-rest #t key?)))
(_ (and (identifier? #'hd) (not opt?)
(lp #'hd-rest #f key?)))))
(_ (and key? (or (stx-null? rest)
(identifier? rest)))))))
(define (kw-lambda-split hd)
(let lp ((rest hd) (kwvar #f) (kwargs '()) (args '()))
(syntax-case rest ()
((kw bind . hd-rest)
(stx-keyword? #'kw)
(let (key (stx-e #'kw))
(if (find (lambda% (kwarg) (eq? key (car kwarg))) kwargs)
(raise-syntax-error #f "Bad syntax; duplicate keyword argument"
stx hd key)
(syntax-case #'bind ()
((id default)
(lp #'hd-rest kwvar
(cons (list key (generate-bind #'id) #'default)
kwargs)
args))
(_
(lp #'hd-rest kwvar
(cons (list key (generate-bind #'bind)
#'(error "Missing required keyword argument"
kw))
kwargs)
args))))))
((#!key id . hd-rest)
(if kwvar
(raise-syntax-error #f "Bad syntax; duplicate #!key argument"
stx hd #'id)
(lp #'hd-rest
(generate-bind #'id)
kwargs args)))
((hd . hd-rest)
(lp #'hd-rest kwvar kwargs (cons #'hd args)))
(_ (values kwvar (reverse kwargs) (foldl cons rest args))))))
(define (generate-bind e)
(if (underscore? e)
(genident e)
e))
(define (check-duplicate-bindings hd)
(define (cons-id id ids)
(if (underscore? id) ids (cons id ids)))
(let lp ((rest hd) (ids '()))
(syntax-case rest ()
((hd . hd-rest)
(cond
((identifier? #'hd)
(lp #'hd-rest (cons-id #'hd ids)))
((stx-pair? #'hd)
(syntax-case #'hd ()
((id _)
(lp #'hd-rest (cons-id #'id ids)))))
((stx-keyword? #'hd)
(syntax-case #'hd-rest ()
((hd . hd-rest)
(syntax-case #'hd ()
((id _)
(lp #'hd-rest (cons-id #'id ids)))
(_ (lp #'hd-rest (cons-id #'hd ids)))))))
((eq? (stx-e #'hd) #!key)
(syntax-case #'hd-rest ()
((id . hd-rest)
(lp #'hd-rest (cons-id #'id ids)))))
(else
(error "BUG: check-duplicate-bindings" stx rest))))
(_
(check-duplicate-identifiers
(if (stx-null? rest) ids (cons-id rest ids))
stx)))))
(define (generate-opt-primary pre opt tail body)
(with-syntax (((pre ...)
pre)
((opt ...)
(map car opt))
(tail tail)
(body body))
#'(lambda% (pre ... opt ... . tail) . body)))
(define (generate-opt-dispatch primary pre opt tail)
(cons (list pre (generate-opt-clause primary pre opt))
(generate-opt-dispatch* primary pre opt tail)))
(define (generate-opt-dispatch* primary pre opt tail)
(let recur ((opt-rest opt) (right '()))
(cond
((pair? opt-rest)
(with-syntax* (((values hd)
(caar opt-rest))
((values rest)
(cdr opt-rest))
((values right*)
(cons hd right))
((pre-bind ...)
pre)
((opt-bind ...)
(reverse right))
(bind hd))
(cons
(list #'(pre-bind ... opt-bind ... bind)
(generate-opt-clause primary
(foldr cons (reverse right*) pre)
rest))
(recur rest right*))))
((stx-null? tail) '())
(else
(with-syntax (((pre ...)
pre)
((opt ...)
(reverse right))
(tail tail)
(primary primary))
(list
(list #'(pre ... opt ... . tail)
(syntax/loc stx
(apply primary pre ... opt ... tail)))))))))
(define (generate-opt-clause primary pre opt)
(let recur ((opt-rest opt) (right '()))
(if (pair? opt-rest)
(with-syntax* (((values hd)
(car opt-rest))
((values rest)
(cdr opt-rest))
(bind (car hd))
(expr (cdr hd))
(body (recur rest (cons #'bind right))))
#'(let-values (((bind) expr))
body))
(with-syntax (((pre ...)
pre)
((opt ...)
(reverse right))
(primary primary))
(syntax/loc stx
(primary pre ... opt ...))))))
(define (generate-kw-primary key kwargs args body)
(define (make-body kwargs kwvals)
(if (pair? kwargs)
(let* ((kwarg (car kwargs))
(var (cadr kwarg))
(default (caddr kwarg))
(kwval (car kwvals))
(rest-kwargs (cdr kwargs))
(rest-kwvals (cdr kwvals)))
(with-syntax ((var var)
(kwval kwval)
(default default)
(body (make-body rest-kwargs rest-kwvals)))
#'(let-values (((var) (if (eq? kwval absent-value) default kwval)))
body)))
(cons 'begin body)))
(define (make-main)
(with-syntax* ((kwvar (or key '_))
((kwval ...) (gentemps (map cadr kwargs)))
(args args)
(body (make-body kwargs #'(kwval ...))))
(syntax/loc stx
(lambda (kwvar kwval ... . args)
body))))
(define (make-dispatch main)
(with-syntax* ((kwvar (or key (genident 'keys)))
((get-kw ...)
(map (lambda% (kwarg)
(with-syntax ((key (car kwarg)))
#'(hash-ref kwvar 'key absent-value)))
kwargs))
(main main))
(syntax/loc stx
(lambda (kwvar . args)
(apply main kwvar get-kw ... args)))))
(with-syntax* ((main-id (genident 'kw-lambda-main))
(dispatch (make-dispatch #'main-id))
(main (make-main)))
#'(let-values (((main-id) main))
dispatch)))
(define (generate-kw-dispatch primary kwargs strict?)
;; when the procedure doesn't accept arbitrary keywords (strict? = #t)
;; generate a "perfect hash table" as a vector for the keywords
;; this is compile-time generated, with no associated runtime-cost.
;; at runtime, keyword-dispatch parses the arguments and builds
;; a hash table that is passed as first argument to primary.
(with-syntax ((pht (and strict? (generate-kw-table (map car kwargs))))
(K primary)
($args (genident 'args)))
#'(lambda% $args (apply keyword-dispatch 'pht K $args))))
(define (generate-kw-table kws)
(let rehash ((pht (make-vector (length kws) #f)))
(let lp ((rest kws))
(if (pair? rest)
(let* ((key (car rest))
(rest (cdr rest))
(pos (fxmodulo (keyword-hash key) (vector-length pht))))
(if (vector-ref pht pos) ; collision?
(if (fx< (vector-length pht) 8192)
(rehash (make-vector (quotient (fx* 3 (vector-length pht)) 2) #f))
(error "Unresolvable keyword collision" kws))
(begin
(vector-set! pht pos key)
(lp rest))))
pht))))
(syntax-case stx ()
((_ hd . body)
(simple-lambda? #'hd)
#'(lambda% hd . body))
((_ hd . body)
(opt-lambda? #'hd)
(with-syntax* (((values pre opt tail)
(opt-lambda-split #'hd))
($primary (genident 'opt-lambda))
(primary
(stx-wrap-source
(generate-opt-primary pre opt tail #'body)
(stx-source stx)))
((clause ...)
(generate-opt-dispatch #'$primary pre opt tail))
(dispatch
(syntax/loc stx
(case-lambda clause ...))))
#'(let-values ((($primary) primary))
dispatch)))
((_ hd . body)
(kw-lambda? #'hd)
(with-syntax* ((_ (check-duplicate-bindings #'hd))
((values key kwargs args)
(kw-lambda-split #'hd))
($primary (genident 'kw-lambda))
(primary
(stx-wrap-source
(generate-kw-primary key kwargs args #'body)
(stx-source stx)))
(dispatch
(stx-wrap-source
(generate-kw-dispatch #'$primary kwargs (not key))
(stx-source stx))))
#'(let-values ((($primary) primary))
dispatch)))))
(defrules def ()
((_ (id . args) body ...)
(identifier? #'id)
(define-values (id)
(lambda args body ...)))
((_ id expr)
(identifier? #'id)
(define-values (id) expr)))
(defrules def* ()
((_ id clauses ...)
(identifier? #'id)
(define-values (id)
(case-lambda clauses ...))))
(defrules defvalues ()
((_ hd expr)
(identifier-list? #'hd)
(define-values hd expr)))
(defrules case ()
((_ expr clause ...)
(let ($e expr)
(~case $e clause ...))))
(defsyntax% (~case stx)
(define (parse-clauses e clauses)
(let lp ((rest clauses) (datums '()) (dispatch '()) (default #f))
(syntax-case rest ()
((clause . rest)
(syntax-case #'clause (else =>)
((else body ...)
(if (stx-null? #'rest)
(if default
(raise-syntax-error #f "Duplicate else clause" stx #'clause)
(lp #'rest datums dispatch #'(begin body ...)))
(raise-syntax-error #f "Misplaced else clause" stx #'clause)))
(((datum ...) => K)
(if (null? #'(datum ...))
(lp #'rest datums dispatch default)
(with-syntax ((e e))
(lp #'rest
(cons (map stx-e #'(datum ...)) datums)
(cons #'(K e) dispatch)
default))))
(((datum ...) body ...)
(if (null? #'(datum ...))
(lp #'rest datums dispatch default)
(lp #'rest
(cons (map stx-e #'(datum ...)) datums)
(cons #'(begin body ...) dispatch)
default)))))
(()
(begin
(check-duplicate-datums datums)
(values (reverse datums) (reverse dispatch) (or default #!void)))))))
(define (check-duplicate-datums datums)
(let (ht (make-hash-table))
(for-each
(lambda% (lst)
(for-each
(lambda% (datum)
(if (hash-get ht datum)
(raise-syntax-error #f "Duplicate datum" stx datum)
(hash-put! ht datum #t)))
lst))
datums)))
(define (count-datums datums)
(foldl (lambda% (lst r) (+ (length lst) r)) 0 datums))
(define (symbolic-datums? datums)
(andmap (lambda% (lst) (andmap symbol? lst)) datums))
(define (char-datums? datums)
(andmap (lambda% (lst) (andmap char? lst)) datums))
(define (fixnum-datums? datums)
(andmap (lambda% (lst) (andmap fixnum? lst)) datums))
(define (eq-datums? datums)
(andmap (lambda% (lst)
(andmap (lambda% (x)
(or (symbol? x)
(keyword? x)
(immediate? x)))
lst))
datums))
(define (generate-simple-case e datums dispatch default)
(with-syntax ((e e))
(let recur ((datums datums) (dispatch dispatch))
(syntax-case datums ()
(((datum ...) . datums)
(syntax-case dispatch ()
((cont . rest)
(with-syntax ((E (recur #'datums #'rest)))
#'(if (or (~case-test datum e) ...)
cont E)))))
(_ default)))))
(define (datum-dispatch-index datums)
(let lp ((rest datums) (ix 0) (r '()))
(syntax-case rest ()
(((datum ...) . rest)
(lp #'rest (fx1+ ix)
(foldl (lambda% (x r) (cons (cons x ix) r))
r #'(datum ...))))
(_ r))))
(define (duplicate-indexes? xs)
(let (ht (make-hash-table-eq))
(let lp ((rest xs))
(if (pair? rest)
(let (ix (car rest))
(or (hash-get ht ix)
(begin
(hash-put! ht ix #t)
(lp (cdr rest)))))
#f))))
(define (generate-hash-dispatch-table indexes hash-e)
(let lp ((len (* 2 (length indexes))))
(let* ((hs (map (lambda% (x) (hash-e (car x))) indexes))
(xs (map (lambda% (h) (fxmodulo h len)) hs)))
(if (duplicate-indexes? xs)
(if (< len 131072)
(lp (quotient (fx* len 3) 2))
(raise-syntax-error #f "Cannot create perfect dispatch table" stx indexes))
(let (tab (make-vector len #f))