forked from gambit/gambit
/
psyntax73.ss
4510 lines (4151 loc) · 182 KB
/
psyntax73.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
;;; Portable implementation of syntax-case
;;; Extracted from Chez Scheme Version 7.3 (Feb 26, 2007)
;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
;;; ***************************************************************************
;;; *** Modified for Gambit 4.4.0 by Marc Feeley (February 4, 2009). ***
;;; *** Look for "***" to see what was modified. ***
;;; ***************************************************************************
;;; Copyright (c) 1992-2002 Cadence Research Systems
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright notice in full. This software
;;; is provided AS IS, with NO WARRANTY, EITHER EXPRESS OR IMPLIED,
;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
;;; NATURE WHATSOEVER.
;;; Before attempting to port this code to a new implementation of
;;; Scheme, please read the notes below carefully.
;;; This file defines the syntax-case expander, sc-expand, and a set
;;; of associated syntactic forms and procedures. Of these, the
;;; following are documented in The Scheme Programming Language,
;;; Third Edition (R. Kent Dybvig, MIT Press, 2003), which can be
;;; found online at http://www.scheme.com/tspl3/. Most are also documented
;;; in the R4RS and draft R5RS.
;;;
;;; bound-identifier=?
;;; datum->syntax-object
;;; define-syntax
;;; fluid-let-syntax
;;; free-identifier=?
;;; generate-temporaries
;;; identifier?
;;; identifier-syntax
;;; let-syntax
;;; letrec-syntax
;;; syntax
;;; syntax-case
;;; syntax-object->datum
;;; syntax-rules
;;; with-syntax
;;;
;;; All standard Scheme syntactic forms are supported by the expander
;;; or syntactic abstractions defined in this file. Only the R4RS
;;; delay is omitted, since its expansion is implementation-dependent.
;;; Also defined are three forms that support modules: module, import,
;;; and import-only. These are documented in the Chez Scheme User's
;;; Guide (R. Kent Dybvig, Cadence Research Systems, 1998), which can
;;; also be found online at http://www.scheme.com/csug/. They are
;;; described briefly here as well.
;;; All are definitions and may appear where and only where other
;;; definitions may appear. modules may be named:
;;;
;;; (module id (ex ...) defn ... init ...)
;;;
;;; or anonymous:
;;;
;;; (module (ex ...) defn ... init ...)
;;;
;;; The latter form is semantically equivalent to:
;;;
;;; (module T (ex ...) defn ... init ...)
;;; (import T)
;;;
;;; where T is a fresh identifier.
;;;
;;; In either form, each of the exports in (ex ...) is either an
;;; identifier or of the form (id ex ...). In the former case, the
;;; single identifier ex is exported. In the latter, the identifier
;;; id is exported and the exports ex ... are "implicitly" exported.
;;; This listing of implicit exports is useful only when id is a
;;; keyword bound to a transformer that expands into references to
;;; the listed implicit exports. In the present implementation,
;;; listing of implicit exports is necessary only for top-level
;;; modules and allows the implementation to avoid placing all
;;; identifiers into the top-level environment where subsequent passes
;;; of the compiler will be unable to deal effectively with them.
;;;
;;; Named modules may be referenced in import statements, which
;;; always take one of the forms:
;;;
;;; (import id)
;;; (import-only id)
;;;
;;; id must name a module. Each exported identifier becomes visible
;;; within the scope of the import form. In the case of import-only,
;;; all other identifiers become invisible in the scope of the
;;; import-only form, except for those established by definitions
;;; that appear textually after the import-only form.
;;; import and import-only also support a variety of identifier
;;; selection and renaming forms: only, except, add-prefix,
;;; drop-prefix, rename, and alias.
;;;
;;; (import (only m x y))
;;;
;;; imports x and y (and nothing else) from m.
;;;
;;; (import (except m x y))
;;;
;;; imports all of m's imports except for x and y.
;;;
;;; (import (add-prefix (only m x y) m:))
;;;
;;; imports x and y as m:x and m:y.
;;;
;;; (import (drop-prefix m foo:))
;;;
;;; imports all of m's imports, dropping the common foo: prefix
;;; (which must appear on all of m's exports).
;;;
;;; (import (rename (except m a b) (m-c c) (m-d d)))
;;;
;;; imports all of m's imports except for x and y, renaming c
;;; m-c and d m-d.
;;;
;;; (import (alias (except m a b) (m-c c) (m-d d)))
;;;
;;; imports all of m's imports except for x and y, with additional
;;; aliases m-c for c and m-d for d.
;;;
;;; multiple imports may be specified with one import form:
;;;
;;; (import (except m1 x) (only m2 x))
;;;
;;; imports all of m1's exports except for x plus x from m2.
;;; Another form, meta, may be used as a prefix for any definition and
;;; causes any resulting variable bindings to be created at expansion
;;; time. Meta variables (variables defined using meta) are available
;;; only at expansion time. Meta definitions are often used to create
;;; data and helpers that can be shared by multiple macros, for example:
;;; (module (alpha beta)
;;; (meta define key-error
;;; (lambda (key)
;;; (syntax-error key "invalid key")))
;;; (meta define parse-keys
;;; (lambda (keys)
;;; (let f ((keys keys) (c #'white) (s 10))
;;; (syntax-case keys (color size)
;;; (() (list c s))
;;; (((color c) . keys) (f #'keys #'c s))
;;; (((size s) . keys) (f #'keys c #'s))
;;; ((k . keys) (key-error #'k))))))
;;; (define-syntax alpha
;;; (lambda (x)
;;; (syntax-case x ()
;;; ((_ (k ...) <other stuff>)
;;; (with-syntax (((c s) (parse-keys (syntax (k ...)))))
;;; ---)))))
;;; (define-syntax beta
;;; (lambda (x)
;;; (syntax-case x ()
;;; ((_ (k ...) <other stuff>)
;;; (with-syntax (((c s) (parse-keys (syntax (k ...)))))
;;; ---))))))
;;; As with define-syntax rhs expressions, meta expressions can evaluate
;;; references only to identifiers whose values are (already) available
;;; in the compile-time environment, e.g., macros and meta variables.
;;; They can, however, like define-syntax rhs expressions, build syntax
;;; objects containing occurrences of any identifiers in their scope.
;;; meta definitions propagate through macro expansion, so one can write,
;;; for example:
;;;
;;; (module (a)
;;; (meta define-structure (foo x))
;;; (define-syntax a
;;; (let ((q (make-foo (syntax 'q))))
;;; (lambda (x)
;;; (foo-x q)))))
;;; a -> q
;;;
;;; where define-record is a macro that expands into a set of defines.
;;;
;;; It is also sometimes convenient to write
;;;
;;; (meta begin defn ...)
;;;
;;; or
;;;
;;; (meta module {exports} defn ...)
;;;
;;; to create groups of meta bindings.
;;; Another form, alias, is used to create aliases from one identifier
;;; to another. This is used primarily to support the extended import
;;; syntaxes (add-prefix, drop-prefix, rename, and alias).
;;; (let ((x 3)) (alias y x) y) -> 3
;;; The remaining exports are listed below. sc-expand, eval-when, and
;;; syntax-error are described in the Chez Scheme User's Guide.
;;;
;;; (sc-expand datum)
;;; if datum represents a valid expression, sc-expand returns an
;;; expanded version of datum in a core language that includes no
;;; syntactic abstractions. The core language includes begin,
;;; define, if, lambda, letrec, quote, and set!.
;;; (eval-when situations expr ...)
;;; conditionally evaluates expr ... at compile-time or run-time
;;; depending upon situations
;;; (syntax-error object message)
;;; used to report errors found during expansion
;;; ($syntax-dispatch e p)
;;; used by expanded code to handle syntax-case matching
;;; ($sc-put-cte symbol val top-token)
;;; used to establish top-level compile-time (expand-time) bindings.
;;; The following nonstandard procedures must be provided by the
;;; implementation for this code to run.
;;;
;;; (void)
;;; returns the implementation's cannonical "unspecified value". The
;;; following usually works:
;;;
;;; (define void (lambda () (if #f #f))).
;;;
;;; (andmap proc list1 list2 ...)
;;; returns true if proc returns true when applied to each element of list1
;;; along with the corresponding elements of list2 .... The following
;;; definition works but does no error checking:
;;;
;;; (define andmap
;;; (lambda (f first . rest)
;;; (or (null? first)
;;; (if (null? rest)
;;; (let andmap ((first first))
;;; (let ((x (car first)) (first (cdr first)))
;;; (if (null? first)
;;; (f x)
;;; (and (f x) (andmap first)))))
;;; (let andmap ((first first) (rest rest))
;;; (let ((x (car first))
;;; (xr (map car rest))
;;; (first (cdr first))
;;; (rest (map cdr rest)))
;;; (if (null? first)
;;; (apply f (cons x xr))
;;; (and (apply f (cons x xr)) (andmap first rest)))))))))
;;;
;;; (ormap proc list1)
;;; returns the first non-false return result of proc applied to
;;; the elements of list1 or false if none. The following definition
;;; works but does no error checking:
;;;
;;; (define ormap
;;; (lambda (proc list1)
;;; (and (not (null? list1))
;;; (or (proc (car list1)) (ormap proc (cdr list1))))))
;;;
;;; The following nonstandard procedures must also be provided by the
;;; implementation for this code to run using the standard portable
;;; hooks and output constructors. They are not used by expanded code,
;;; and so need be present only at expansion time.
;;;
;;; (eval x)
;;; where x is always in the form ("noexpand" expr).
;;; returns the value of expr. the "noexpand" flag is used to tell the
;;; evaluator/expander that no expansion is necessary, since expr has
;;; already been fully expanded to core forms.
;;;
;;; eval will not be invoked during the loading of psyntax.pp. After
;;; psyntax.pp has been loaded, the expansion of any macro definition,
;;; whether local or global, results in a call to eval. If, however,
;;; sc-expand has already been registered as the expander to be used
;;; by eval, and eval accepts one argument, nothing special must be done
;;; to support the "noexpand" flag, since it is handled by sc-expand.
;;;
;;; (error who format-string why what)
;;; where who is either a symbol or #f, format-string is always "~a ~s",
;;; why is always a string, and what may be any object. error should
;;; signal an error with a message something like
;;;
;;; "error in <who>: <why> <what>"
;;;
;;; (gensym)
;;; returns a unique symbol each time it's called. In Chez Scheme, gensym
;;; returns a symbol with a "globally" unique name so that gensyms that
;;; end up in the object code of separately compiled files cannot conflict.
;;; This is necessary only if you intend to support compiled files.
;;;
;;; (gensym? x)
;;; returns #t if x is a gensym, otherwise false.
;;;
;;; (putprop symbol key value)
;;; (getprop symbol key)
;;; (remprop symbol key)
;;; key is always a symbol; value may be any object. putprop should
;;; associate the given value with the given symbol and key in some way
;;; that it can be retrieved later with getprop. getprop should return
;;; #f if no value is associated with the given symbol and key. remprop
;;; should remove the association between the given symbol and key.
;;; When porting to a new Scheme implementation, you should define the
;;; procedures listed above, load the expanded version of psyntax.ss
;;; (psyntax.pp, which should be available whereever you found
;;; psyntax.ss), and register sc-expand as the current expander (how
;;; you do this depends upon your implementation of Scheme). You may
;;; change the hooks and constructors defined toward the beginning of
;;; the code below, but to avoid bootstrapping problems, do so only
;;; after you have a working version of the expander.
;;; Chez Scheme allows the syntactic form (syntax <template>) to be
;;; abbreviated to #'<template>, just as (quote <datum>) may be
;;; abbreviated to '<datum>. The #' syntax makes programs written
;;; using syntax-case shorter and more readable and draws out the
;;; intuitive connection between syntax and quote. If you have access
;;; to the source code of your Scheme system's reader, you might want
;;; to implement this extension.
;;; If you find that this code loads or runs slowly, consider
;;; switching to faster hardware or a faster implementation of
;;; Scheme. In Chez Scheme on a 200Mhz Pentium Pro, expanding,
;;; compiling (with full optimization), and loading this file takes
;;; between one and two seconds.
;;; In the expander implementation, we sometimes use syntactic abstractions
;;; when procedural abstractions would suffice. For example, we define
;;; top-wrap and top-marked? as
;;; (define-syntax top-wrap (identifier-syntax '((top))))
;;; (define-syntax top-marked?
;;; (syntax-rules ()
;;; ((_ w) (memq 'top (wrap-marks w)))))
;;; rather than
;;; (define top-wrap '((top)))
;;; (define top-marked?
;;; (lambda (w) (memq 'top (wrap-marks w))))
;;; On ther other hand, we don't do this consistently; we define make-wrap,
;;; wrap-marks, and wrap-subst simply as
;;; (define make-wrap cons)
;;; (define wrap-marks car)
;;; (define wrap-subst cdr)
;;; In Chez Scheme, the syntactic and procedural forms of these
;;; abstractions are equivalent, since the optimizer consistently
;;; integrates constants and small procedures. Some Scheme
;;; implementations, however, may benefit from more consistent use
;;; of one form or the other.
;;; Implementation notes:
;;; "begin" is treated as a splicing construct at top level and at
;;; the beginning of bodies. Any sequence of expressions that would
;;; be allowed where the "begin" occurs is allowed.
;;; "let-syntax" and "letrec-syntax" are also treated as splicing
;;; constructs, in violation of the R5RS. A consequence is that let-syntax
;;; and letrec-syntax do not create local contours, as do let and letrec.
;;; Although the functionality is greater as it is presently implemented,
;;; we will probably change it to conform to the R5RS. modules provide
;;; similar functionality to nonsplicing letrec-syntax when the latter is
;;; used as a definition.
;;; Objects with no standard print syntax, including objects containing
;;; cycles and syntax objects, are allowed in quoted data as long as they
;;; are contained within a syntax form or produced by datum->syntax-object.
;;; Such objects are never copied.
;;; When the expander encounters a reference to an identifier that has
;;; no global or lexical binding, it treats it as a global-variable
;;; reference. This allows one to write mutually recursive top-level
;;; definitions, e.g.:
;;;
;;; (define f (lambda (x) (g x)))
;;; (define g (lambda (x) (f x)))
;;;
;;; but may not always yield the intended when the variable in question
;;; is later defined as a keyword.
;;; Top-level variable definitions of syntax keywords are permitted.
;;; In order to make this work, top-level define not only produces a
;;; top-level definition in the core language, but also modifies the
;;; compile-time environment (using $sc-put-cte) to record the fact
;;; that the identifier is a variable.
;;; Top-level definitions of macro-introduced identifiers are visible
;;; only in code produced by the macro. That is, a binding for a
;;; hidden (generated) identifier is created instead, and subsequent
;;; references within the macro output are renamed accordingly. For
;;; example:
;;;
;;; (define-syntax a
;;; (syntax-rules ()
;;; ((_ var exp)
;;; (begin
;;; (define secret exp)
;;; (define var
;;; (lambda ()
;;; (set! secret (+ secret 17))
;;; secret))))))
;;; (a x 0)
;;; (x) => 17
;;; (x) => 34
;;; secret => Error: variable secret is not bound
;;;
;;; The definition above would fail if the definition for secret
;;; were placed after the definition for var, since the expander would
;;; encounter the references to secret before the definition that
;;; establishes the compile-time map from the identifier secret to
;;; the generated identifier.
;;; Identifiers and syntax objects are implemented as vectors for
;;; portability. As a result, it is possible to "forge" syntax
;;; objects.
;;; The input to sc-expand may contain "annotations" describing, e.g., the
;;; source file and character position from where each object was read if
;;; it was read from a file. These annotations are handled properly by
;;; sc-expand only if the annotation? hook (see hooks below) is implemented
;;; properly and the operators annotation-expression and annotation-stripped
;;; are supplied. If annotations are supplied, the proper annotated
;;; expression is passed to the various output constructors, allowing
;;; implementations to accurately correlate source and expanded code.
;;; Contact one of the authors for details if you wish to make use of
;;; this feature.
;;; Implementation of modules:
;;;
;;; The implementation of modules requires that implicit top-level exports
;;; be listed with the exported macro at some level where both are visible,
;;; e.g.,
;;;
;;; (module M (alpha (beta b))
;;; (module ((alpha a) b)
;;; (define-syntax alpha (identifier-syntax a))
;;; (define a 'a)
;;; (define b 'b))
;;; (define-syntax beta (identifier-syntax b)))
;;;
;;; Listing of implicit imports is not needed for macros that do not make
;;; it out to top level, including all macros that are local to a "body".
;;; (They may be listed in this case, however.) We need this information
;;; for top-level modules since a top-level module expands into a letrec
;;; for non-top-level variables and top-level definitions (assignments) for
;;; top-level variables. Because of the general nature of macro
;;; transformers, we cannot determine the set of implicit exports from the
;;; transformer code, so without the user's help, we'd have to put all
;;; variables at top level.
;;;
;;; Each such top-level identifier is given a generated name (gensym).
;;; When a top-level module is imported at top level, a compile-time
;;; alias is established from the top-level name to the generated name.
;;; The expander follows these aliases transparently. When any module is
;;; imported anywhere other than at top level, the id-var-name of the
;;; import identifier is set to the id-var-name of the export identifier.
;;; Since we can't determine the actual labels for identifiers defined in
;;; top-level modules until we determine which are placed in the letrec
;;; and which make it to top level, we give each an "indirect" label---a
;;; pair whose car will eventually contain the actual label. Import does
;;; not follow the indirect, but id-var-name does.
;;;
;;; All identifiers defined within a local module are folded into the
;;; letrec created for the enclosing body. Visibility is controlled in
;;; this case and for nested top-level modules by introducing a new wrap
;;; for each module.
;;; Bootstrapping:
;;; When changing syntax-object representations, it is necessary to support
;;; both old and new syntax-object representations in id-var-name. It
;;; should be sufficient to redefine syntax-object-expression to work for
;;; both old and new representations and syntax-object-wrap to return the
;;; empty-wrap for old representations.
;;; The following set of definitions establishes bindings for the
;;; top-level variables assigned values in the let expression below.
;;; Uncomment them here and copy them to the front of psyntax.pp if
;;; required by your system.
; (define $sc-put-cte #f)
; (define sc-expand #f)
; (define $make-environment #f)
; (define environment? #f)
; (define interaction-environment #f)
; (define identifier? #f)
; (define syntax->list #f)
; (define syntax-object->datum #f)
; (define datum->syntax-object #f)
; (define generate-temporaries #f)
; (define free-identifier=? #f)
; (define bound-identifier=? #f)
; (define literal-identifier=? #f)
; (define syntax-error #f)
; (define $syntax-dispatch #f)
(let ()
(define-syntax when
(syntax-rules ()
((_ test e1 e2 ...) (if test (begin e1 e2 ...)))))
(define-syntax unless
(syntax-rules ()
((_ test e1 e2 ...) (when (not test) (begin e1 e2 ...)))))
(define-syntax define-structure
(lambda (x)
(define construct-name
(lambda (template-identifier . args)
(datum->syntax-object
template-identifier
(string->symbol
(apply string-append
(map (lambda (x)
(if (string? x)
x
(symbol->string (syntax-object->datum x))))
args))))))
(syntax-case x ()
((_ (name id1 ...))
(andmap identifier? (syntax (name id1 ...)))
(with-syntax
((constructor (construct-name (syntax name) "make-" (syntax name)))
(predicate (construct-name (syntax name) (syntax name) "?"))
((access ...)
(map (lambda (x) (construct-name x (syntax name) "-" x))
(syntax (id1 ...))))
((assign ...)
(map (lambda (x)
(construct-name x "set-" (syntax name) "-" x "!"))
(syntax (id1 ...))))
(structure-length
(+ (length (syntax (id1 ...))) 1))
((index ...)
(let f ((i 1) (ids (syntax (id1 ...))))
(if (null? ids)
'()
(cons i (f (+ i 1) (cdr ids)))))))
(syntax (begin
(define constructor
(lambda (id1 ...)
(vector 'name id1 ... )))
(define predicate
(lambda (x)
(and (vector? x)
(= (vector-length x) structure-length)
(eq? (vector-ref x 0) 'name))))
(define access
(lambda (x)
(vector-ref x index)))
...
(define assign
(lambda (x update)
(vector-set! x index update)))
...)))))))
(define-syntax let-values ; impoverished one-clause version
(syntax-rules ()
((_ ((formals expr)) form1 form2 ...)
(call-with-values (lambda () expr) (lambda formals form1 form2 ...)))))
(define noexpand "noexpand")
(define-structure (syntax-object expression wrap))
;;; hooks to nonportable run-time helpers
(begin
;*** Gambit supports fx+, etc.
;*** (define-syntax fx+ (identifier-syntax +))
;*** (define-syntax fx- (identifier-syntax -))
;*** (define-syntax fx= (identifier-syntax =))
;*** (define-syntax fx< (identifier-syntax <))
;*** (define-syntax fx> (identifier-syntax >))
;*** (define-syntax fx<= (identifier-syntax <=))
;*** (define-syntax fx>= (identifier-syntax >=))
;*** (define annotation? (lambda (x) #f))
; top-level-eval-hook is used to create "permanent" code (e.g., top-level
; transformers), so it might be a good idea to compile it
(define top-level-eval-hook
(lambda (x)
(eval `(,noexpand ,x))))
; local-eval-hook is used to create "temporary" code (e.g., local
; transformers), so it might be a good idea to interpret it
(define local-eval-hook
(lambda (x)
(eval `(,noexpand ,x))))
(define define-top-level-value-hook
(lambda (sym val)
(top-level-eval-hook
(build-global-definition no-source sym
(build-data no-source val)))))
;*** (define error-hook
;*** (lambda (who why what)
;*** (error who "~a ~s" why what)))
(define put-cte-hook
(lambda (symbol val)
($sc-put-cte symbol val '*top*)))
(define get-global-definition-hook
(lambda (symbol)
(getprop symbol '*sc-expander*)))
(define put-global-definition-hook
(lambda (symbol x)
(if (not x)
(remprop symbol '*sc-expander*)
(putprop symbol '*sc-expander* x))))
; if you treat certain bindings (say from environments like ieee or r5rs)
; read-only, this should return #t for those bindings
(define read-only-binding?
(lambda (symbol)
#f))
; should return #f if symbol has no binding for token
(define get-import-binding
(lambda (symbol token)
(getprop symbol token)))
; remove binding if x is false
(define update-import-binding!
(lambda (symbol token p)
(let ((x (p (get-import-binding symbol token))))
(if (not x)
(remprop symbol token)
(putprop symbol token x)))))
;;; generate-id ideally produces globally unique symbols, i.e., symbols
;;; unique across system runs, to support separate compilation/expansion.
;;; Use gensyms if you do not need to support separate compilation/
;;; expansion or if your system's gensym creates globally unique
;;; symbols (as in Chez Scheme). Otherwise, use the following code
;;; as a starting point. session-key should be a unique string for each
;;; system run to support separate compilation; the default value given
;;; is satisfactory during initial development only.
(define generate-id
(let ((digits "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!$%&*/:<=>?~_^.+-"))
(let ((base (string-length digits)) (session-key "_"))
(define make-digit (lambda (x) (string-ref digits x)))
(define fmt
(lambda (n)
(let fmt ((n n) (a '()))
(if (< n base)
(list->string (cons (make-digit n) a))
(let ((r (modulo n base)) (rest (quotient n base)))
(fmt rest (cons (make-digit r) a)))))))
(let ((n -1))
(lambda (name) ; name is #f or a symbol
(set! n (+ n 1))
(string->symbol (string-append session-key (fmt n))))))))
)
;;; output constructors
(begin
(define-syntax build-application
(syntax-rules ()
((_ ae fun-exp arg-exps)
;*** `(,fun-exp . ,arg-exps))))
(build-source ae `(,fun-exp . ,arg-exps)))))
(define-syntax build-conditional
(syntax-rules ()
((_ ae test-exp then-exp else-exp)
;*** `(if ,test-exp ,then-exp ,else-exp))))
(build-source ae `(,(build-source ae 'if) ,test-exp ,then-exp ,else-exp)))))
(define-syntax build-lexical-reference
(syntax-rules ()
((_ type ae var)
;*** var)))
(build-source ae var))))
(define-syntax build-lexical-assignment
(syntax-rules ()
((_ ae var exp)
;*** `(set! ,var ,exp))))
(build-source ae `(,(build-source ae 'set!) ,(build-source ae var) ,exp)))))
(define-syntax build-global-reference
(syntax-rules ()
((_ ae var)
;*** var)))
(build-source ae var))))
(define-syntax build-global-assignment
(syntax-rules ()
((_ ae var exp)
;*** `(set! ,var ,exp))))
(build-source ae `(,(build-source ae 'set!) ,(build-source ae var) ,exp)))))
(define-syntax build-global-definition
(syntax-rules ()
((_ ae var exp)
;*** `(define ,var ,exp))))
(build-source ae `(,(build-source ae 'define) ,(build-source ae var) ,exp)))))
(define-syntax build-cte-install
; should build a call that has the same effect as calling put-cte-hook
(syntax-rules ()
;*** ((_ sym exp token) `($sc-put-cte ',sym ,exp ',token))))
((_ sym exp token) (build-source #f `(,(build-source #f '$sc-put-cte) ',sym ,exp ,(build-source #f (list (build-source #f 'quote) token)))))))
(define-syntax build-visit-only
; should mark the result as "visit only" for compile-file
; in implementations that support visit/revisit
(syntax-rules ()
((_ exp) exp)))
(define-syntax build-revisit-only
; should mark the result as "revisit only" for compile-file,
; in implementations that support visit/revisit
(syntax-rules ()
((_ exp) exp)))
(define-syntax build-lambda
(syntax-rules ()
((_ ae vars exp)
;*** `(lambda ,vars ,exp))))
(build-source ae
`(,(build-source ae 'lambda)
,(build-params ae vars)
,exp)))))
(define built-lambda?
(lambda (x)
;*** (and (pair? x) (eq? (car x) 'lambda))))
(or (and (pair? x) (eq? (car x) 'lambda))
(and (##source? x)
(pair? (##source-code x))
(##source? (car (##source-code x)))
(eq? (##source-code (car (##source-code x))) 'lambda)))))
(define-syntax build-primref
(syntax-rules ()
;*** ((_ ae name) name)
;*** ((_ ae level name) name)))
((_ ae name) (build-source ae name))
((_ ae level name) (build-source ae name))))
(define-syntax build-data
(syntax-rules ()
;*** ((_ ae exp) `',exp)))
((_ ae exp) (let ((x (attach-source ae exp))) (if (self-eval? exp) x (build-source ae (list (build-source ae 'quote) x)))))))
(define build-sequence
(lambda (ae exps)
(let loop ((exps exps))
(if (null? (cdr exps))
(car exps)
; weed out leading void calls, assuming ordinary list representation
;*** (if (equal? (car exps) '(void))
;*** (loop (cdr exps))
;*** `(begin ,@exps))))))
(if (let ((x (car exps)))
(or (equal? x '(void))
(and (##source? x)
(pair? (##source-code x))
(##source? (car (##source-code x)))
(eq? (##source-code (car (##source-code x))) 'void)
(null? (cdr (##source-code x))))))
(loop (cdr exps))
(build-source ae (cons (build-source ae 'begin) exps)))))))
(define build-letrec
(lambda (ae vars val-exps body-exp)
(if (null? vars)
body-exp
;*** `(letrec ,(map list vars val-exps) ,body-exp))))
(build-source ae `(,(build-source ae 'letrec) ,(build-source ae (map (lambda (var val) (build-source ae (list (build-source ae var) val))) vars val-exps)) ,body-exp)))))
(define build-body
(lambda (ae vars val-exps body-exp)
(build-letrec ae vars val-exps body-exp)))
(define build-top-module
; each type is either global (exported) or local (not exported)
; we produce global definitions and assignments for globals and
; letrec bindings for locals. if you don't need the definitions,
; (just assignments) you can eliminate them. if you wish to
; have your module definitions ordered from left-to-right (ala
; letrec*), you can replace the global var-exps with dummy vars
; and global val-exps with global assignments, and produce a letrec*
; in place of a letrec.
(lambda (ae types vars val-exps body-exp)
(let-values (((vars defns sets)
(let f ((types types) (vars vars))
(if (null? types)
(values '() '() '())
(let ((var (car vars)))
(let-values (((vars defns sets) (f (cdr types) (cdr vars))))
(if (eq? (car types) 'global)
(let ((x (build-lexical-var no-source var)))
(values
(cons x vars)
(cons (build-global-definition no-source var (chi-void)) defns)
(cons (build-global-assignment no-source var (build-lexical-reference 'value no-source x)) sets)))
(values (cons var vars) defns sets))))))))
(if (null? defns)
(build-letrec ae vars val-exps body-exp)
(build-sequence no-source
(append defns
(list
(build-letrec ae vars val-exps
(build-sequence no-source (append sets (list body-exp)))))))))))
(define-syntax build-lexical-var
(syntax-rules ()
;*** ((_ ae id) (gensym))))
((_ ae id) (gensym id))))
(define-syntax lexical-var? gensym?)
(define-syntax self-evaluating?
(syntax-rules ()
((_ e)
(let ((x e))
;*** (or (boolean? x) (number? x) (string? x) (char? x) (null? x))))))
(self-eval? x)))))
)
(define-syntax unannotate
(syntax-rules ()
((_ x)
(let ((e x))
(if (annotation? e)
(annotation-expression e)
e)))))
(define-syntax no-source (identifier-syntax #f))
(define-syntax arg-check
(syntax-rules ()
((_ pred? e who)
(let ((x e))
;*** (if (not (pred? x)) (error-hook who "invalid argument" x))))))
(if (not (pred? x))
(error (string-append "(in "
(symbol->string who)
") invalid argument")
x))))))
;;; compile-time environments
;;; wrap and environment comprise two level mapping.
;;; wrap : id --> label
;;; env : label --> <element>
;;; environments are represented in two parts: a lexical part and a global
;;; part. The lexical part is a simple list of associations from labels
;;; to bindings. The global part is implemented by
;;; {put,get}-global-definition-hook and associates symbols with
;;; bindings.
;;; global (assumed global variable) and displaced-lexical (see below)
;;; do not show up in any environment; instead, they are fabricated by
;;; lookup when it finds no other bindings.
;;; <environment> ::= ((<label> . <binding>)*)
;;; identifier bindings include a type and a value
;;; <binding> ::= <procedure> macro keyword
;;; (macro . <procedure>) macro keyword
;;; (deferred . <thunk>) macro keyword w/lazily evaluated transformer
;;; (macro! . <procedure>) extended identifier macro keyword
;;; (core . <procedure>) core keyword
;;; (begin) begin keyword
;;; (define) define keyword
;;; (define-syntax) define-syntax keyword
;;; (local-syntax . <boolean>) let-syntax (#f)/letrec-syntax (#t) keyword
;;; (eval-when) eval-when keyword
;;; (set!) set! keyword
;;; (meta) meta keyword
;;; ($module-key) $module keyword
;;; ($import) $import keyword
;;; ($module . <interface>) modules
;;; (syntax . (<var> . <level>)) pattern variables
;;; (global . <symbol>) assumed global variable
;;; (meta-variable . <symbol>) meta variable
;;; (lexical . <var>) lexical variables
;;; (displaced-lexical . #f) id-var-name not found in store
;;; <level> ::= <nonnegative integer>
;;; <var> ::= variable returned by build-lexical-var
;;; a macro is a user-defined syntactic-form. a core is a system-defined
;;; syntactic form. begin, define, define-syntax, let-syntax, letrec-syntax,
;;; eval-when, and meta are treated specially since they are sensitive to
;;; whether the form is at top-level and can denote valid internal
;;; definitions.
;;; a pattern variable is a variable introduced by syntax-case and can
;;; be referenced only within a syntax form.
;;; any identifier for which no top-level syntax definition or local
;;; binding of any kind has been seen is assumed to be a global
;;; variable.
;;; a lexical variable is a lambda- or letrec-bound variable.
;;; a displaced-lexical identifier is a lexical identifier removed from
;;; it's scope by the return of a syntax object containing the identifier.
;;; a displaced lexical can also appear when a letrec-syntax-bound
;;; keyword is referenced on the rhs of one of the letrec-syntax clauses.
;;; a displaced lexical should never occur with properly written macros.
(define sanitize-binding
(lambda (b)
(cond
((procedure? b) (make-binding 'macro b))
((binding? b)
(and (case (binding-type b)
((core macro macro! deferred) (and (procedure? (binding-value b))))
(($module) (interface? (binding-value b)))
((lexical) (lexical-var? (binding-value b)))
((global meta-variable) (symbol? (binding-value b)))
((syntax) (let ((x (binding-value b)))
(and (pair? x)
(lexical-var? (car x))
(let ((n (cdr x)))
(and (integer? n) (exact? n) (>= n 0))))))
((begin define define-syntax set! $module-key $import eval-when meta) (null? (binding-value b)))
((local-syntax) (boolean? (binding-value b)))
((displaced-lexical) (eq? (binding-value b) #f))
(else #t))
b))
(else #f))))
(define-syntax make-binding
(syntax-rules (quote)
((_ 'type #f) '(type . #f))
((_ type value) (cons type value))))
(define binding-type car)
(define binding-value cdr)
(define set-binding-type! set-car!)
(define set-binding-value! set-cdr!)
(define binding? (lambda (x) (and (pair? x) (symbol? (car x)))))
(define-syntax null-env (identifier-syntax '()))
(define extend-env
(lambda (label binding r)
(cons (cons label binding) r)))
(define extend-env*
(lambda (labels bindings r)
(if (null? labels)
r
(extend-env* (cdr labels) (cdr bindings)
(extend-env (car labels) (car bindings) r)))))
(define extend-var-env*
; variant of extend-env* that forms "lexical" binding
(lambda (labels vars r)
(if (null? labels)
r
(extend-var-env* (cdr labels) (cdr vars)
(extend-env (car labels) (make-binding 'lexical (car vars)) r)))))
(define (displaced-lexical? id r)
(let ((n (id-var-name id empty-wrap)))
(and n
(let ((b (lookup n r)))
(eq? (binding-type b) 'displaced-lexical)))))
(define displaced-lexical-error
(lambda (id)
(syntax-error id
(if (id-var-name id empty-wrap)
"identifier out of context"
"identifier not visible"))))
(define lookup*
; x may be a label or a symbol
; although symbols are usually global, we check the environment first
; anyway because a temporary binding may have been established by
; fluid-let-syntax
(lambda (x r)
(cond
((assq x r) => cdr)
((symbol? x)
(or (get-global-definition-hook x) (make-binding 'global x)))
(else (make-binding 'displaced-lexical #f)))))
(define lookup
(lambda (x r)
(define whack-binding!
(lambda (b *b)
(set-binding-type! b (binding-type *b))
(set-binding-value! b (binding-value *b))))
(let ((b (lookup* x r)))
(when (eq? (binding-type b) 'deferred)
(whack-binding! b (make-transformer-binding ((binding-value b)))))
b)))