psyntax: fold chi-top-sequence into chi-top
[bpt/guile.git] / module / ice-9 / psyntax.scm
1 ;;;; -*-scheme-*-
2 ;;;;
3 ;;;; Copyright (C) 2001, 2003, 2006, 2009, 2010, 2011 Free Software Foundation, Inc.
4 ;;;;
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 ;;;;
19 \f
20
21 ;;; Portable implementation of syntax-case
22 ;;; Originally extracted from Chez Scheme Version 5.9f
23 ;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
24
25 ;;; Copyright (c) 1992-1997 Cadence Research Systems
26 ;;; Permission to copy this software, in whole or in part, to use this
27 ;;; software for any lawful purpose, and to redistribute this software
28 ;;; is granted subject to the restriction that all copies made of this
29 ;;; software must include this copyright notice in full. This software
30 ;;; is provided AS IS, with NO WARRANTY, EITHER EXPRESS OR IMPLIED,
31 ;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
32 ;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
33 ;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
34 ;;; NATURE WHATSOEVER.
35
36 ;;; Modified by Mikael Djurfeldt <djurfeldt@nada.kth.se> according
37 ;;; to the ChangeLog distributed in the same directory as this file:
38 ;;; 1997-08-19, 1997-09-03, 1997-09-10, 2000-08-13, 2000-08-24,
39 ;;; 2000-09-12, 2001-03-08
40
41 ;;; Modified by Andy Wingo <wingo@pobox.com> according to the Git
42 ;;; revision control logs corresponding to this file: 2009, 2010.
43
44
45 ;;; This file defines the syntax-case expander, macroexpand, and a set
46 ;;; of associated syntactic forms and procedures. Of these, the
47 ;;; following are documented in The Scheme Programming Language,
48 ;;; Fourth Edition (R. Kent Dybvig, MIT Press, 2009), and in the
49 ;;; R6RS:
50 ;;;
51 ;;; bound-identifier=?
52 ;;; datum->syntax
53 ;;; define-syntax
54 ;;; fluid-let-syntax
55 ;;; free-identifier=?
56 ;;; generate-temporaries
57 ;;; identifier?
58 ;;; identifier-syntax
59 ;;; let-syntax
60 ;;; letrec-syntax
61 ;;; syntax
62 ;;; syntax-case
63 ;;; syntax->datum
64 ;;; syntax-rules
65 ;;; with-syntax
66 ;;;
67 ;;; Additionally, the expander provides definitions for a number of core
68 ;;; Scheme syntactic bindings, such as `let', `lambda', and the like.
69
70 ;;; The remaining exports are listed below:
71 ;;;
72 ;;; (macroexpand datum)
73 ;;; if datum represents a valid expression, macroexpand returns an
74 ;;; expanded version of datum in a core language that includes no
75 ;;; syntactic abstractions. The core language includes begin,
76 ;;; define, if, lambda, letrec, quote, and set!.
77 ;;; (eval-when situations expr ...)
78 ;;; conditionally evaluates expr ... at compile-time or run-time
79 ;;; depending upon situations (see the Chez Scheme System Manual,
80 ;;; Revision 3, for a complete description)
81 ;;; (syntax-violation who message form [subform])
82 ;;; used to report errors found during expansion
83 ;;; ($sc-dispatch e p)
84 ;;; used by expanded code to handle syntax-case matching
85
86 ;;; This file is shipped along with an expanded version of itself,
87 ;;; psyntax-pp.scm, which is loaded when psyntax.scm has not yet been
88 ;;; compiled. In this way, psyntax bootstraps off of an expanded
89 ;;; version of itself.
90
91 ;;; This implementation of the expander sometimes uses syntactic
92 ;;; abstractions when procedural abstractions would suffice. For
93 ;;; example, we define top-wrap and top-marked? as
94 ;;;
95 ;;; (define-syntax top-wrap (identifier-syntax '((top))))
96 ;;; (define-syntax top-marked?
97 ;;; (syntax-rules ()
98 ;;; ((_ w) (memq 'top (wrap-marks w)))))
99 ;;;
100 ;;; rather than
101 ;;;
102 ;;; (define top-wrap '((top)))
103 ;;; (define top-marked?
104 ;;; (lambda (w) (memq 'top (wrap-marks w))))
105 ;;;
106 ;;; On the other hand, we don't do this consistently; we define
107 ;;; make-wrap, wrap-marks, and wrap-subst simply as
108 ;;;
109 ;;; (define make-wrap cons)
110 ;;; (define wrap-marks car)
111 ;;; (define wrap-subst cdr)
112 ;;;
113 ;;; In Chez Scheme, the syntactic and procedural forms of these
114 ;;; abstractions are equivalent, since the optimizer consistently
115 ;;; integrates constants and small procedures. This will be true of
116 ;;; Guile as well, once we implement a proper inliner.
117
118
119 ;;; Implementation notes:
120
121 ;;; Objects with no standard print syntax, including objects containing
122 ;;; cycles and syntax object, are allowed in quoted data as long as they
123 ;;; are contained within a syntax form or produced by datum->syntax.
124 ;;; Such objects are never copied.
125
126 ;;; All identifiers that don't have macro definitions and are not bound
127 ;;; lexically are assumed to be global variables.
128
129 ;;; Top-level definitions of macro-introduced identifiers are allowed.
130 ;;; This may not be appropriate for implementations in which the
131 ;;; model is that bindings are created by definitions, as opposed to
132 ;;; one in which initial values are assigned by definitions.
133
134 ;;; Identifiers and syntax objects are implemented as vectors for
135 ;;; portability. As a result, it is possible to "forge" syntax objects.
136
137 ;;; The implementation of generate-temporaries assumes that it is
138 ;;; possible to generate globally unique symbols (gensyms).
139
140 ;;; The source location associated with incoming expressions is tracked
141 ;;; via the source-properties mechanism, a weak map from expression to
142 ;;; source information. At times the source is separated from the
143 ;;; expression; see the note below about "efficiency and confusion".
144
145
146 ;;; Bootstrapping:
147
148 ;;; When changing syntax-object representations, it is necessary to support
149 ;;; both old and new syntax-object representations in id-var-name. It
150 ;;; should be sufficient to recognize old representations and treat
151 ;;; them as not lexically bound.
152
153
154
155 (eval-when (compile)
156 (set-current-module (resolve-module '(guile))))
157
158 (let ()
159 ;; Private version of and-map that handles multiple lists.
160 (define and-map*
161 (lambda (f first . rest)
162 (or (null? first)
163 (if (null? rest)
164 (let andmap ((first first))
165 (let ((x (car first)) (first (cdr first)))
166 (if (null? first)
167 (f x)
168 (and (f x) (andmap first)))))
169 (let andmap ((first first) (rest rest))
170 (let ((x (car first))
171 (xr (map car rest))
172 (first (cdr first))
173 (rest (map cdr rest)))
174 (if (null? first)
175 (apply f x xr)
176 (and (apply f x xr) (andmap first rest)))))))))
177
178 (define-syntax define-expansion-constructors
179 (lambda (x)
180 (syntax-case x ()
181 ((_)
182 (let lp ((n 0) (out '()))
183 (if (< n (vector-length %expanded-vtables))
184 (lp (1+ n)
185 (let* ((vtable (vector-ref %expanded-vtables n))
186 (stem (struct-ref vtable (+ vtable-offset-user 0)))
187 (fields (struct-ref vtable (+ vtable-offset-user 2)))
188 (sfields (map (lambda (f) (datum->syntax x f)) fields))
189 (ctor (datum->syntax x (symbol-append 'make- stem))))
190 (cons #`(define (#,ctor #,@sfields)
191 (make-struct (vector-ref %expanded-vtables #,n) 0
192 #,@sfields))
193 out)))
194 #`(begin #,@(reverse out))))))))
195
196 (define-syntax define-expansion-accessors
197 (lambda (x)
198 (syntax-case x ()
199 ((_ stem field ...)
200 (let lp ((n 0))
201 (let ((vtable (vector-ref %expanded-vtables n))
202 (stem (syntax->datum #'stem)))
203 (if (eq? (struct-ref vtable (+ vtable-offset-user 0)) stem)
204 #`(begin
205 (define (#,(datum->syntax x (symbol-append stem '?)) x)
206 (and (struct? x)
207 (eq? (struct-vtable x)
208 (vector-ref %expanded-vtables #,n))))
209 #,@(map
210 (lambda (f)
211 (let ((get (datum->syntax x (symbol-append stem '- f)))
212 (set (datum->syntax x (symbol-append 'set- stem '- f '!)))
213 (idx (list-index (struct-ref vtable
214 (+ vtable-offset-user 2))
215 f)))
216 #`(begin
217 (define (#,get x)
218 (struct-ref x #,idx))
219 (define (#,set x v)
220 (struct-set! x #,idx v)))))
221 (syntax->datum #'(field ...))))
222 (lp (1+ n)))))))))
223
224 (define-syntax define-structure
225 (lambda (x)
226 (define construct-name
227 (lambda (template-identifier . args)
228 (datum->syntax
229 template-identifier
230 (string->symbol
231 (apply string-append
232 (map (lambda (x)
233 (if (string? x)
234 x
235 (symbol->string (syntax->datum x))))
236 args))))))
237 (syntax-case x ()
238 ((_ (name id1 ...))
239 (and-map identifier? #'(name id1 ...))
240 (with-syntax
241 ((constructor (construct-name #'name "make-" #'name))
242 (predicate (construct-name #'name #'name "?"))
243 ((access ...)
244 (map (lambda (x) (construct-name x #'name "-" x))
245 #'(id1 ...)))
246 ((assign ...)
247 (map (lambda (x)
248 (construct-name x "set-" #'name "-" x "!"))
249 #'(id1 ...)))
250 (structure-length
251 (+ (length #'(id1 ...)) 1))
252 ((index ...)
253 (let f ((i 1) (ids #'(id1 ...)))
254 (if (null? ids)
255 '()
256 (cons i (f (+ i 1) (cdr ids)))))))
257 #'(begin
258 (define constructor
259 (lambda (id1 ...)
260 (vector 'name id1 ... )))
261 (define predicate
262 (lambda (x)
263 (and (vector? x)
264 (= (vector-length x) structure-length)
265 (eq? (vector-ref x 0) 'name))))
266 (define access
267 (lambda (x)
268 (vector-ref x index)))
269 ...
270 (define assign
271 (lambda (x update)
272 (vector-set! x index update)))
273 ...))))))
274
275 (let ()
276 (define-expansion-constructors)
277 (define-expansion-accessors lambda meta)
278
279 ;; hooks to nonportable run-time helpers
280 (begin
281 (define fx+ +)
282 (define fx- -)
283 (define fx= =)
284 (define fx< <)
285
286 (define top-level-eval-hook
287 (lambda (x mod)
288 (primitive-eval x)))
289
290 (define local-eval-hook
291 (lambda (x mod)
292 (primitive-eval x)))
293
294 (define-syntax gensym-hook
295 (syntax-rules ()
296 ((_) (gensym))))
297
298 (define put-global-definition-hook
299 (lambda (symbol type val)
300 (module-define! (current-module)
301 symbol
302 (make-syntax-transformer symbol type val))))
303
304 (define get-global-definition-hook
305 (lambda (symbol module)
306 (if (and (not module) (current-module))
307 (warn "module system is booted, we should have a module" symbol))
308 (let ((v (module-variable (if module
309 (resolve-module (cdr module))
310 (current-module))
311 symbol)))
312 (and v (variable-bound? v)
313 (let ((val (variable-ref v)))
314 (and (macro? val) (macro-type val)
315 (cons (macro-type val)
316 (macro-binding val)))))))))
317
318
319 (define (decorate-source e s)
320 (if (and (pair? e) s)
321 (set-source-properties! e s))
322 e)
323
324 (define (maybe-name-value! name val)
325 (if (lambda? val)
326 (let ((meta (lambda-meta val)))
327 (if (not (assq 'name meta))
328 (set-lambda-meta! val (acons 'name name meta))))))
329
330 ;; output constructors
331 (define build-void
332 (lambda (source)
333 (make-void source)))
334
335 (define build-application
336 (lambda (source fun-exp arg-exps)
337 (make-application source fun-exp arg-exps)))
338
339 (define build-conditional
340 (lambda (source test-exp then-exp else-exp)
341 (make-conditional source test-exp then-exp else-exp)))
342
343 (define build-dynlet
344 (lambda (source fluids vals body)
345 (make-dynlet source fluids vals body)))
346
347 (define build-lexical-reference
348 (lambda (type source name var)
349 (make-lexical-ref source name var)))
350
351 (define build-lexical-assignment
352 (lambda (source name var exp)
353 (maybe-name-value! name exp)
354 (make-lexical-set source name var exp)))
355
356 (define (analyze-variable mod var modref-cont bare-cont)
357 (if (not mod)
358 (bare-cont var)
359 (let ((kind (car mod))
360 (mod (cdr mod)))
361 (case kind
362 ((public) (modref-cont mod var #t))
363 ((private) (if (not (equal? mod (module-name (current-module))))
364 (modref-cont mod var #f)
365 (bare-cont var)))
366 ((bare) (bare-cont var))
367 ((hygiene) (if (and (not (equal? mod (module-name (current-module))))
368 (module-variable (resolve-module mod) var))
369 (modref-cont mod var #f)
370 (bare-cont var)))
371 (else (syntax-violation #f "bad module kind" var mod))))))
372
373 (define build-global-reference
374 (lambda (source var mod)
375 (analyze-variable
376 mod var
377 (lambda (mod var public?)
378 (make-module-ref source mod var public?))
379 (lambda (var)
380 (make-toplevel-ref source var)))))
381
382 (define build-global-assignment
383 (lambda (source var exp mod)
384 (maybe-name-value! var exp)
385 (analyze-variable
386 mod var
387 (lambda (mod var public?)
388 (make-module-set source mod var public? exp))
389 (lambda (var)
390 (make-toplevel-set source var exp)))))
391
392 (define build-global-definition
393 (lambda (source var exp)
394 (maybe-name-value! var exp)
395 (make-toplevel-define source var exp)))
396
397 (define build-simple-lambda
398 (lambda (src req rest vars meta exp)
399 (make-lambda src
400 meta
401 ;; hah, a case in which kwargs would be nice.
402 (make-lambda-case
403 ;; src req opt rest kw inits vars body else
404 src req #f rest #f '() vars exp #f))))
405
406 (define build-case-lambda
407 (lambda (src meta body)
408 (make-lambda src meta body)))
409
410 (define build-lambda-case
411 ;; req := (name ...)
412 ;; opt := (name ...) | #f
413 ;; rest := name | #f
414 ;; kw := (allow-other-keys? (keyword name var) ...) | #f
415 ;; inits: (init ...)
416 ;; vars: (sym ...)
417 ;; vars map to named arguments in the following order:
418 ;; required, optional (positional), rest, keyword.
419 ;; the body of a lambda: anything, already expanded
420 ;; else: lambda-case | #f
421 (lambda (src req opt rest kw inits vars body else-case)
422 (make-lambda-case src req opt rest kw inits vars body else-case)))
423
424 (define build-primref
425 (lambda (src name)
426 (if (equal? (module-name (current-module)) '(guile))
427 (make-toplevel-ref src name)
428 (make-module-ref src '(guile) name #f))))
429
430 (define (build-data src exp)
431 (make-const src exp))
432
433 (define build-sequence
434 (lambda (src exps)
435 (if (null? (cdr exps))
436 (car exps)
437 (make-sequence src exps))))
438
439 (define build-let
440 (lambda (src ids vars val-exps body-exp)
441 (for-each maybe-name-value! ids val-exps)
442 (if (null? vars)
443 body-exp
444 (make-let src ids vars val-exps body-exp))))
445
446 (define build-named-let
447 (lambda (src ids vars val-exps body-exp)
448 (let ((f (car vars))
449 (f-name (car ids))
450 (vars (cdr vars))
451 (ids (cdr ids)))
452 (let ((proc (build-simple-lambda src ids #f vars '() body-exp)))
453 (maybe-name-value! f-name proc)
454 (for-each maybe-name-value! ids val-exps)
455 (make-letrec
456 src #f
457 (list f-name) (list f) (list proc)
458 (build-application src (build-lexical-reference 'fun src f-name f)
459 val-exps))))))
460
461 (define build-letrec
462 (lambda (src in-order? ids vars val-exps body-exp)
463 (if (null? vars)
464 body-exp
465 (begin
466 (for-each maybe-name-value! ids val-exps)
467 (make-letrec src in-order? ids vars val-exps body-exp)))))
468
469
470 ;; FIXME: use a faster gensym
471 (define-syntax build-lexical-var
472 (syntax-rules ()
473 ((_ src id) (gensym (string-append (symbol->string id) " ")))))
474
475 (define-structure (syntax-object expression wrap module))
476
477 (define-syntax no-source (identifier-syntax #f))
478
479 (define source-annotation
480 (lambda (x)
481 (cond
482 ((syntax-object? x)
483 (source-annotation (syntax-object-expression x)))
484 ((pair? x) (let ((props (source-properties x)))
485 (if (pair? props)
486 props
487 #f)))
488 (else #f))))
489
490 (define-syntax arg-check
491 (syntax-rules ()
492 ((_ pred? e who)
493 (let ((x e))
494 (if (not (pred? x)) (syntax-violation who "invalid argument" x))))))
495
496 ;; compile-time environments
497
498 ;; wrap and environment comprise two level mapping.
499 ;; wrap : id --> label
500 ;; env : label --> <element>
501
502 ;; environments are represented in two parts: a lexical part and a global
503 ;; part. The lexical part is a simple list of associations from labels
504 ;; to bindings. The global part is implemented by
505 ;; {put,get}-global-definition-hook and associates symbols with
506 ;; bindings.
507
508 ;; global (assumed global variable) and displaced-lexical (see below)
509 ;; do not show up in any environment; instead, they are fabricated by
510 ;; lookup when it finds no other bindings.
511
512 ;; <environment> ::= ((<label> . <binding>)*)
513
514 ;; identifier bindings include a type and a value
515
516 ;; <binding> ::= (macro . <procedure>) macros
517 ;; (core . <procedure>) core forms
518 ;; (module-ref . <procedure>) @ or @@
519 ;; (begin) begin
520 ;; (define) define
521 ;; (define-syntax) define-syntax
522 ;; (local-syntax . rec?) let-syntax/letrec-syntax
523 ;; (eval-when) eval-when
524 ;; (syntax . (<var> . <level>)) pattern variables
525 ;; (global) assumed global variable
526 ;; (lexical . <var>) lexical variables
527 ;; (displaced-lexical) displaced lexicals
528 ;; <level> ::= <nonnegative integer>
529 ;; <var> ::= variable returned by build-lexical-var
530
531 ;; a macro is a user-defined syntactic-form. a core is a system-defined
532 ;; syntactic form. begin, define, define-syntax, and eval-when are
533 ;; treated specially since they are sensitive to whether the form is
534 ;; at top-level and (except for eval-when) can denote valid internal
535 ;; definitions.
536
537 ;; a pattern variable is a variable introduced by syntax-case and can
538 ;; be referenced only within a syntax form.
539
540 ;; any identifier for which no top-level syntax definition or local
541 ;; binding of any kind has been seen is assumed to be a global
542 ;; variable.
543
544 ;; a lexical variable is a lambda- or letrec-bound variable.
545
546 ;; a displaced-lexical identifier is a lexical identifier removed from
547 ;; it's scope by the return of a syntax object containing the identifier.
548 ;; a displaced lexical can also appear when a letrec-syntax-bound
549 ;; keyword is referenced on the rhs of one of the letrec-syntax clauses.
550 ;; a displaced lexical should never occur with properly written macros.
551
552 (define-syntax make-binding
553 (syntax-rules (quote)
554 ((_ type value) (cons type value))
555 ((_ 'type) '(type))
556 ((_ type) (cons type '()))))
557 (define-syntax binding-type
558 (syntax-rules ()
559 ((_ x) (car x))))
560 (define-syntax binding-value
561 (syntax-rules ()
562 ((_ x) (cdr x))))
563
564 (define-syntax null-env (identifier-syntax '()))
565
566 (define extend-env
567 (lambda (labels bindings r)
568 (if (null? labels)
569 r
570 (extend-env (cdr labels) (cdr bindings)
571 (cons (cons (car labels) (car bindings)) r)))))
572
573 (define extend-var-env
574 ;; variant of extend-env that forms "lexical" binding
575 (lambda (labels vars r)
576 (if (null? labels)
577 r
578 (extend-var-env (cdr labels) (cdr vars)
579 (cons (cons (car labels) (make-binding 'lexical (car vars))) r)))))
580
581 ;; we use a "macros only" environment in expansion of local macro
582 ;; definitions so that their definitions can use local macros without
583 ;; attempting to use other lexical identifiers.
584 (define macros-only-env
585 (lambda (r)
586 (if (null? r)
587 '()
588 (let ((a (car r)))
589 (if (eq? (cadr a) 'macro)
590 (cons a (macros-only-env (cdr r)))
591 (macros-only-env (cdr r)))))))
592
593 (define lookup
594 ;; x may be a label or a symbol
595 ;; although symbols are usually global, we check the environment first
596 ;; anyway because a temporary binding may have been established by
597 ;; fluid-let-syntax
598 (lambda (x r mod)
599 (cond
600 ((assq x r) => cdr)
601 ((symbol? x)
602 (or (get-global-definition-hook x mod) (make-binding 'global)))
603 (else (make-binding 'displaced-lexical)))))
604
605 (define global-extend
606 (lambda (type sym val)
607 (put-global-definition-hook sym type val)))
608
609
610 ;; Conceptually, identifiers are always syntax objects. Internally,
611 ;; however, the wrap is sometimes maintained separately (a source of
612 ;; efficiency and confusion), so that symbols are also considered
613 ;; identifiers by id?. Externally, they are always wrapped.
614
615 (define nonsymbol-id?
616 (lambda (x)
617 (and (syntax-object? x)
618 (symbol? (syntax-object-expression x)))))
619
620 (define id?
621 (lambda (x)
622 (cond
623 ((symbol? x) #t)
624 ((syntax-object? x) (symbol? (syntax-object-expression x)))
625 (else #f))))
626
627 (define-syntax id-sym-name
628 (syntax-rules ()
629 ((_ e)
630 (let ((x e))
631 (if (syntax-object? x)
632 (syntax-object-expression x)
633 x)))))
634
635 (define id-sym-name&marks
636 (lambda (x w)
637 (if (syntax-object? x)
638 (values
639 (syntax-object-expression x)
640 (join-marks (wrap-marks w) (wrap-marks (syntax-object-wrap x))))
641 (values x (wrap-marks w)))))
642
643 ;; syntax object wraps
644
645 ;; <wrap> ::= ((<mark> ...) . (<subst> ...))
646 ;; <subst> ::= <shift> | <subs>
647 ;; <subs> ::= #(<old name> <label> (<mark> ...))
648 ;; <shift> ::= positive fixnum
649
650 (define-syntax make-wrap (identifier-syntax cons))
651 (define-syntax wrap-marks (identifier-syntax car))
652 (define-syntax wrap-subst (identifier-syntax cdr))
653
654 (define-syntax subst-rename? (identifier-syntax vector?))
655 (define-syntax rename-old (syntax-rules () ((_ x) (vector-ref x 0))))
656 (define-syntax rename-new (syntax-rules () ((_ x) (vector-ref x 1))))
657 (define-syntax rename-marks (syntax-rules () ((_ x) (vector-ref x 2))))
658 (define-syntax make-rename
659 (syntax-rules ()
660 ((_ old new marks) (vector old new marks))))
661
662 ;; labels must be comparable with "eq?", have read-write invariance,
663 ;; and distinct from symbols.
664 (define gen-label
665 (lambda () (symbol->string (gensym "i"))))
666
667 (define gen-labels
668 (lambda (ls)
669 (if (null? ls)
670 '()
671 (cons (gen-label) (gen-labels (cdr ls))))))
672
673 (define-structure (ribcage symnames marks labels))
674
675 (define-syntax empty-wrap (identifier-syntax '(())))
676
677 (define-syntax top-wrap (identifier-syntax '((top))))
678
679 (define-syntax top-marked?
680 (syntax-rules ()
681 ((_ w) (memq 'top (wrap-marks w)))))
682
683 ;; Marks must be comparable with "eq?" and distinct from pairs and
684 ;; the symbol top. We do not use integers so that marks will remain
685 ;; unique even across file compiles.
686
687 (define-syntax the-anti-mark (identifier-syntax #f))
688
689 (define anti-mark
690 (lambda (w)
691 (make-wrap (cons the-anti-mark (wrap-marks w))
692 (cons 'shift (wrap-subst w)))))
693
694 (define-syntax new-mark
695 (syntax-rules ()
696 ((_) (gensym "m"))))
697
698 ;; make-empty-ribcage and extend-ribcage maintain list-based ribcages for
699 ;; internal definitions, in which the ribcages are built incrementally
700 (define-syntax make-empty-ribcage
701 (syntax-rules ()
702 ((_) (make-ribcage '() '() '()))))
703
704 (define extend-ribcage!
705 ;; must receive ids with complete wraps
706 (lambda (ribcage id label)
707 (set-ribcage-symnames! ribcage
708 (cons (syntax-object-expression id)
709 (ribcage-symnames ribcage)))
710 (set-ribcage-marks! ribcage
711 (cons (wrap-marks (syntax-object-wrap id))
712 (ribcage-marks ribcage)))
713 (set-ribcage-labels! ribcage
714 (cons label (ribcage-labels ribcage)))))
715
716 ;; make-binding-wrap creates vector-based ribcages
717 (define make-binding-wrap
718 (lambda (ids labels w)
719 (if (null? ids)
720 w
721 (make-wrap
722 (wrap-marks w)
723 (cons
724 (let ((labelvec (list->vector labels)))
725 (let ((n (vector-length labelvec)))
726 (let ((symnamevec (make-vector n)) (marksvec (make-vector n)))
727 (let f ((ids ids) (i 0))
728 (if (not (null? ids))
729 (call-with-values
730 (lambda () (id-sym-name&marks (car ids) w))
731 (lambda (symname marks)
732 (vector-set! symnamevec i symname)
733 (vector-set! marksvec i marks)
734 (f (cdr ids) (fx+ i 1))))))
735 (make-ribcage symnamevec marksvec labelvec))))
736 (wrap-subst w))))))
737
738 (define smart-append
739 (lambda (m1 m2)
740 (if (null? m2)
741 m1
742 (append m1 m2))))
743
744 (define join-wraps
745 (lambda (w1 w2)
746 (let ((m1 (wrap-marks w1)) (s1 (wrap-subst w1)))
747 (if (null? m1)
748 (if (null? s1)
749 w2
750 (make-wrap
751 (wrap-marks w2)
752 (smart-append s1 (wrap-subst w2))))
753 (make-wrap
754 (smart-append m1 (wrap-marks w2))
755 (smart-append s1 (wrap-subst w2)))))))
756
757 (define join-marks
758 (lambda (m1 m2)
759 (smart-append m1 m2)))
760
761 (define same-marks?
762 (lambda (x y)
763 (or (eq? x y)
764 (and (not (null? x))
765 (not (null? y))
766 (eq? (car x) (car y))
767 (same-marks? (cdr x) (cdr y))))))
768
769 (define id-var-name
770 (lambda (id w)
771 (define-syntax first
772 (syntax-rules ()
773 ((_ e) (call-with-values (lambda () e) (lambda (x . ignore) x)))))
774 (define search
775 (lambda (sym subst marks)
776 (if (null? subst)
777 (values #f marks)
778 (let ((fst (car subst)))
779 (if (eq? fst 'shift)
780 (search sym (cdr subst) (cdr marks))
781 (let ((symnames (ribcage-symnames fst)))
782 (if (vector? symnames)
783 (search-vector-rib sym subst marks symnames fst)
784 (search-list-rib sym subst marks symnames fst))))))))
785 (define search-list-rib
786 (lambda (sym subst marks symnames ribcage)
787 (let f ((symnames symnames) (i 0))
788 (cond
789 ((null? symnames) (search sym (cdr subst) marks))
790 ((and (eq? (car symnames) sym)
791 (same-marks? marks (list-ref (ribcage-marks ribcage) i)))
792 (values (list-ref (ribcage-labels ribcage) i) marks))
793 (else (f (cdr symnames) (fx+ i 1)))))))
794 (define search-vector-rib
795 (lambda (sym subst marks symnames ribcage)
796 (let ((n (vector-length symnames)))
797 (let f ((i 0))
798 (cond
799 ((fx= i n) (search sym (cdr subst) marks))
800 ((and (eq? (vector-ref symnames i) sym)
801 (same-marks? marks (vector-ref (ribcage-marks ribcage) i)))
802 (values (vector-ref (ribcage-labels ribcage) i) marks))
803 (else (f (fx+ i 1))))))))
804 (cond
805 ((symbol? id)
806 (or (first (search id (wrap-subst w) (wrap-marks w))) id))
807 ((syntax-object? id)
808 (let ((id (syntax-object-expression id))
809 (w1 (syntax-object-wrap id)))
810 (let ((marks (join-marks (wrap-marks w) (wrap-marks w1))))
811 (call-with-values (lambda () (search id (wrap-subst w) marks))
812 (lambda (new-id marks)
813 (or new-id
814 (first (search id (wrap-subst w1) marks))
815 id))))))
816 (else (syntax-violation 'id-var-name "invalid id" id)))))
817
818 ;; free-id=? must be passed fully wrapped ids since (free-id=? x y)
819 ;; may be true even if (free-id=? (wrap x w) (wrap y w)) is not.
820
821 (define free-id=?
822 (lambda (i j)
823 (and (eq? (id-sym-name i) (id-sym-name j)) ; accelerator
824 (eq? (id-var-name i empty-wrap) (id-var-name j empty-wrap)))))
825
826 ;; bound-id=? may be passed unwrapped (or partially wrapped) ids as
827 ;; long as the missing portion of the wrap is common to both of the ids
828 ;; since (bound-id=? x y) iff (bound-id=? (wrap x w) (wrap y w))
829
830 (define bound-id=?
831 (lambda (i j)
832 (if (and (syntax-object? i) (syntax-object? j))
833 (and (eq? (syntax-object-expression i)
834 (syntax-object-expression j))
835 (same-marks? (wrap-marks (syntax-object-wrap i))
836 (wrap-marks (syntax-object-wrap j))))
837 (eq? i j))))
838
839 ;; "valid-bound-ids?" returns #t if it receives a list of distinct ids.
840 ;; valid-bound-ids? may be passed unwrapped (or partially wrapped) ids
841 ;; as long as the missing portion of the wrap is common to all of the
842 ;; ids.
843
844 (define valid-bound-ids?
845 (lambda (ids)
846 (and (let all-ids? ((ids ids))
847 (or (null? ids)
848 (and (id? (car ids))
849 (all-ids? (cdr ids)))))
850 (distinct-bound-ids? ids))))
851
852 ;; distinct-bound-ids? expects a list of ids and returns #t if there are
853 ;; no duplicates. It is quadratic on the length of the id list; long
854 ;; lists could be sorted to make it more efficient. distinct-bound-ids?
855 ;; may be passed unwrapped (or partially wrapped) ids as long as the
856 ;; missing portion of the wrap is common to all of the ids.
857
858 (define distinct-bound-ids?
859 (lambda (ids)
860 (let distinct? ((ids ids))
861 (or (null? ids)
862 (and (not (bound-id-member? (car ids) (cdr ids)))
863 (distinct? (cdr ids)))))))
864
865 (define bound-id-member?
866 (lambda (x list)
867 (and (not (null? list))
868 (or (bound-id=? x (car list))
869 (bound-id-member? x (cdr list))))))
870
871 ;; wrapping expressions and identifiers
872
873 (define wrap
874 (lambda (x w defmod)
875 (cond
876 ((and (null? (wrap-marks w)) (null? (wrap-subst w))) x)
877 ((syntax-object? x)
878 (make-syntax-object
879 (syntax-object-expression x)
880 (join-wraps w (syntax-object-wrap x))
881 (syntax-object-module x)))
882 ((null? x) x)
883 (else (make-syntax-object x w defmod)))))
884
885 (define source-wrap
886 (lambda (x w s defmod)
887 (wrap (decorate-source x s) w defmod)))
888
889 ;; expanding
890
891 (define chi-sequence
892 (lambda (body r w s mod)
893 (build-sequence s
894 (let dobody ((body body) (r r) (w w) (mod mod))
895 (if (null? body)
896 '()
897 (let ((first (chi (car body) r w mod)))
898 (cons first (dobody (cdr body) r w mod))))))))
899
900 (define chi-top-sequence
901 (lambda (body r w s m esew mod)
902 (define (scan body r w s m esew mod exps)
903 (define-syntax eval-if-c&e
904 (syntax-rules ()
905 ((_ m e mod)
906 (let ((x e))
907 (if (eq? m 'c&e) (top-level-eval-hook x mod))
908 x))))
909 (cond
910 ((null? body)
911 ;; in reversed order
912 exps)
913 (else
914 (call-with-values
915 (lambda ()
916 (call-with-values
917 (lambda ()
918 (let ((e (car body)))
919 (syntax-type e r w (or (source-annotation e) s) #f mod #f)))
920 (lambda (type value e w s mod)
921 (case type
922 ((begin-form)
923 (syntax-case e ()
924 ((_) exps)
925 ((_ e1 e2 ...)
926 (scan #'(e1 e2 ...) r w s m esew mod exps))))
927 ((local-syntax-form)
928 (chi-local-syntax value e r w s mod
929 (lambda (body r w s mod)
930 (scan body r w s m esew mod exps))))
931 ((eval-when-form)
932 (syntax-case e ()
933 ((_ (x ...) e1 e2 ...)
934 (let ((when-list (chi-when-list e #'(x ...) w))
935 (body #'(e1 e2 ...)))
936 (cond
937 ((eq? m 'e)
938 (if (memq 'eval when-list)
939 (scan body r w s
940 (if (memq 'expand when-list) 'c&e 'e)
941 '(eval)
942 mod exps)
943 (begin
944 (if (memq 'expand when-list)
945 (top-level-eval-hook
946 (chi-top-sequence body r w s 'e '(eval) mod)
947 mod))
948 (values exps))))
949 ((memq 'load when-list)
950 (if (or (memq 'compile when-list)
951 (memq 'expand when-list)
952 (and (eq? m 'c&e) (memq 'eval when-list)))
953 (scan body r w s 'c&e '(compile load) mod exps)
954 (if (memq m '(c c&e))
955 (scan body r w s 'c '(load) mod exps)
956 (values exps))))
957 ((or (memq 'compile when-list)
958 (memq 'expand when-list)
959 (and (eq? m 'c&e) (memq 'eval when-list)))
960 (top-level-eval-hook
961 (chi-top-sequence body r w s 'e '(eval) mod)
962 mod)
963 (values exps))
964 (else
965 (values exps)))))))
966 ((define-syntax-form)
967 (let ((n (id-var-name value w)) (r (macros-only-env r)))
968 (case m
969 ((c)
970 (if (memq 'compile esew)
971 (let ((e (chi-install-global n (chi e r w mod))))
972 (top-level-eval-hook e mod)
973 (if (memq 'load esew)
974 (values (cons e exps))
975 (values exps)))
976 (if (memq 'load esew)
977 (values (cons (chi-install-global n (chi e r w mod))
978 exps))
979 (values exps))))
980 ((c&e)
981 (let ((e (chi-install-global n (chi e r w mod))))
982 (top-level-eval-hook e mod)
983 (values (cons e exps))))
984 (else
985 (if (memq 'eval esew)
986 (top-level-eval-hook
987 (chi-install-global n (chi e r w mod))
988 mod))
989 (values exps)))))
990 ((define-form)
991 (let* ((n (id-var-name value w))
992 ;; Lookup the name in the module of the define form.
993 (type (binding-type (lookup n r mod))))
994 (case type
995 ((global core macro module-ref)
996 ;; affect compile-time environment (once we have booted)
997 (if (and (memq m '(c c&e))
998 (not (module-local-variable (current-module) n))
999 (current-module))
1000 (let ((old (module-variable (current-module) n)))
1001 ;; use value of the same-named imported variable, if
1002 ;; any
1003 (if (and (variable? old) (variable-bound? old))
1004 (module-define! (current-module) n (variable-ref old))
1005 (module-add! (current-module) n (make-undefined-variable)))))
1006 (values
1007 (cons
1008 (eval-if-c&e m
1009 (build-global-definition s n (chi e r w mod))
1010 mod)
1011 exps)))
1012 ((displaced-lexical)
1013 (syntax-violation #f "identifier out of context"
1014 e (wrap value w mod)))
1015 (else
1016 (syntax-violation #f "cannot define keyword at top level"
1017 e (wrap value w mod))))))
1018 (else
1019 (values (cons
1020 (eval-if-c&e m (chi-expr type value e r w s mod) mod)
1021 exps)))))))
1022 (lambda (exps)
1023 (scan (cdr body) r w s m esew mod exps))))))
1024
1025 (call-with-values (lambda ()
1026 (scan body r w s m esew mod '()))
1027 (lambda (exps)
1028 (if (null? exps)
1029 (build-void s)
1030 (build-sequence s (reverse exps)))))))
1031
1032 (define chi-install-global
1033 (lambda (name e)
1034 (build-global-definition
1035 no-source
1036 name
1037 (build-application
1038 no-source
1039 (build-primref no-source 'make-syntax-transformer)
1040 (list (build-data no-source name)
1041 (build-data no-source 'macro)
1042 e)))))
1043
1044 (define chi-when-list
1045 (lambda (e when-list w)
1046 ;; when-list is syntax'd version of list of situations
1047 (let f ((when-list when-list) (situations '()))
1048 (if (null? when-list)
1049 situations
1050 (f (cdr when-list)
1051 (cons (let ((x (car when-list)))
1052 (cond
1053 ((free-id=? x #'compile) 'compile)
1054 ((free-id=? x #'load) 'load)
1055 ((free-id=? x #'eval) 'eval)
1056 ((free-id=? x #'expand) 'expand)
1057 (else (syntax-violation 'eval-when
1058 "invalid situation"
1059 e (wrap x w #f)))))
1060 situations))))))
1061
1062 ;; syntax-type returns six values: type, value, e, w, s, and mod. The
1063 ;; first two are described in the table below.
1064 ;;
1065 ;; type value explanation
1066 ;; -------------------------------------------------------------------
1067 ;; core procedure core singleton
1068 ;; core-form procedure core form
1069 ;; module-ref procedure @ or @@ singleton
1070 ;; lexical name lexical variable reference
1071 ;; global name global variable reference
1072 ;; begin none begin keyword
1073 ;; define none define keyword
1074 ;; define-syntax none define-syntax keyword
1075 ;; local-syntax rec? letrec-syntax/let-syntax keyword
1076 ;; eval-when none eval-when keyword
1077 ;; syntax level pattern variable
1078 ;; displaced-lexical none displaced lexical identifier
1079 ;; lexical-call name call to lexical variable
1080 ;; global-call name call to global variable
1081 ;; call none any other call
1082 ;; begin-form none begin expression
1083 ;; define-form id variable definition
1084 ;; define-syntax-form id syntax definition
1085 ;; local-syntax-form rec? syntax definition
1086 ;; eval-when-form none eval-when form
1087 ;; constant none self-evaluating datum
1088 ;; other none anything else
1089 ;;
1090 ;; For define-form and define-syntax-form, e is the rhs expression.
1091 ;; For all others, e is the entire form. w is the wrap for e.
1092 ;; s is the source for the entire form. mod is the module for e.
1093 ;;
1094 ;; syntax-type expands macros and unwraps as necessary to get to
1095 ;; one of the forms above. It also parses define and define-syntax
1096 ;; forms, although perhaps this should be done by the consumer.
1097
1098 (define syntax-type
1099 (lambda (e r w s rib mod for-car?)
1100 (cond
1101 ((symbol? e)
1102 (let* ((n (id-var-name e w))
1103 (b (lookup n r mod))
1104 (type (binding-type b)))
1105 (case type
1106 ((lexical) (values type (binding-value b) e w s mod))
1107 ((global) (values type n e w s mod))
1108 ((macro)
1109 (if for-car?
1110 (values type (binding-value b) e w s mod)
1111 (syntax-type (chi-macro (binding-value b) e r w s rib mod)
1112 r empty-wrap s rib mod #f)))
1113 (else (values type (binding-value b) e w s mod)))))
1114 ((pair? e)
1115 (let ((first (car e)))
1116 (call-with-values
1117 (lambda () (syntax-type first r w s rib mod #t))
1118 (lambda (ftype fval fe fw fs fmod)
1119 (case ftype
1120 ((lexical)
1121 (values 'lexical-call fval e w s mod))
1122 ((global)
1123 ;; If we got here via an (@@ ...) expansion, we need to
1124 ;; make sure the fmod information is propagated back
1125 ;; correctly -- hence this consing.
1126 (values 'global-call (make-syntax-object fval w fmod)
1127 e w s mod))
1128 ((macro)
1129 (syntax-type (chi-macro fval e r w s rib mod)
1130 r empty-wrap s rib mod for-car?))
1131 ((module-ref)
1132 (call-with-values (lambda () (fval e r w))
1133 (lambda (e r w s mod)
1134 (syntax-type e r w s rib mod for-car?))))
1135 ((core)
1136 (values 'core-form fval e w s mod))
1137 ((local-syntax)
1138 (values 'local-syntax-form fval e w s mod))
1139 ((begin)
1140 (values 'begin-form #f e w s mod))
1141 ((eval-when)
1142 (values 'eval-when-form #f e w s mod))
1143 ((define)
1144 (syntax-case e ()
1145 ((_ name val)
1146 (id? #'name)
1147 (values 'define-form #'name #'val w s mod))
1148 ((_ (name . args) e1 e2 ...)
1149 (and (id? #'name)
1150 (valid-bound-ids? (lambda-var-list #'args)))
1151 ;; need lambda here...
1152 (values 'define-form (wrap #'name w mod)
1153 (decorate-source
1154 (cons #'lambda (wrap #'(args e1 e2 ...) w mod))
1155 s)
1156 empty-wrap s mod))
1157 ((_ name)
1158 (id? #'name)
1159 (values 'define-form (wrap #'name w mod)
1160 #'(if #f #f)
1161 empty-wrap s mod))))
1162 ((define-syntax)
1163 (syntax-case e ()
1164 ((_ name val)
1165 (id? #'name)
1166 (values 'define-syntax-form #'name
1167 #'val w s mod))))
1168 (else
1169 (values 'call #f e w s mod)))))))
1170 ((syntax-object? e)
1171 (syntax-type (syntax-object-expression e)
1172 r
1173 (join-wraps w (syntax-object-wrap e))
1174 (or (source-annotation e) s) rib
1175 (or (syntax-object-module e) mod) for-car?))
1176 ((self-evaluating? e) (values 'constant #f e w s mod))
1177 (else (values 'other #f e w s mod)))))
1178
1179 (define chi
1180 (lambda (e r w mod)
1181 (call-with-values
1182 (lambda () (syntax-type e r w (source-annotation e) #f mod #f))
1183 (lambda (type value e w s mod)
1184 (chi-expr type value e r w s mod)))))
1185
1186 (define chi-expr
1187 (lambda (type value e r w s mod)
1188 (case type
1189 ((lexical)
1190 (build-lexical-reference 'value s e value))
1191 ((core core-form)
1192 ;; apply transformer
1193 (value e r w s mod))
1194 ((module-ref)
1195 (call-with-values (lambda () (value e r w))
1196 (lambda (e r w s mod)
1197 (chi e r w mod))))
1198 ((lexical-call)
1199 (chi-application
1200 (let ((id (car e)))
1201 (build-lexical-reference 'fun (source-annotation id)
1202 (if (syntax-object? id)
1203 (syntax->datum id)
1204 id)
1205 value))
1206 e r w s mod))
1207 ((global-call)
1208 (chi-application
1209 (build-global-reference (source-annotation (car e))
1210 (if (syntax-object? value)
1211 (syntax-object-expression value)
1212 value)
1213 (if (syntax-object? value)
1214 (syntax-object-module value)
1215 mod))
1216 e r w s mod))
1217 ((constant) (build-data s (strip (source-wrap e w s mod) empty-wrap)))
1218 ((global) (build-global-reference s value mod))
1219 ((call) (chi-application (chi (car e) r w mod) e r w s mod))
1220 ((begin-form)
1221 (syntax-case e ()
1222 ((_ e1 e2 ...) (chi-sequence #'(e1 e2 ...) r w s mod))))
1223 ((local-syntax-form)
1224 (chi-local-syntax value e r w s mod chi-sequence))
1225 ((eval-when-form)
1226 (syntax-case e ()
1227 ((_ (x ...) e1 e2 ...)
1228 (let ((when-list (chi-when-list e #'(x ...) w)))
1229 (if (memq 'eval when-list)
1230 (chi-sequence #'(e1 e2 ...) r w s mod)
1231 (chi-void))))))
1232 ((define-form define-syntax-form)
1233 (syntax-violation #f "definition in expression context"
1234 e (wrap value w mod)))
1235 ((syntax)
1236 (syntax-violation #f "reference to pattern variable outside syntax form"
1237 (source-wrap e w s mod)))
1238 ((displaced-lexical)
1239 (syntax-violation #f "reference to identifier outside its scope"
1240 (source-wrap e w s mod)))
1241 (else (syntax-violation #f "unexpected syntax"
1242 (source-wrap e w s mod))))))
1243
1244 (define chi-application
1245 (lambda (x e r w s mod)
1246 (syntax-case e ()
1247 ((e0 e1 ...)
1248 (build-application s x
1249 (map (lambda (e) (chi e r w mod)) #'(e1 ...)))))))
1250
1251 ;; (What follows is my interpretation of what's going on here -- Andy)
1252 ;;
1253 ;; A macro takes an expression, a tree, the leaves of which are identifiers
1254 ;; and datums. Identifiers are symbols along with a wrap and a module. For
1255 ;; efficiency, subtrees that share wraps and modules may be grouped as one
1256 ;; syntax object.
1257 ;;
1258 ;; Going into the expansion, the expression is given an anti-mark, which
1259 ;; logically propagates to all leaves. Then, in the new expression returned
1260 ;; from the transfomer, if we see an expression with an anti-mark, we know it
1261 ;; pertains to the original expression; conversely, expressions without the
1262 ;; anti-mark are known to be introduced by the transformer.
1263 ;;
1264 ;; OK, good until now. We know this algorithm does lexical scoping
1265 ;; appropriately because it's widely known in the literature, and psyntax is
1266 ;; widely used. But what about modules? Here we're on our own. What we do is
1267 ;; to mark the module of expressions produced by a macro as pertaining to the
1268 ;; module that was current when the macro was defined -- that is, free
1269 ;; identifiers introduced by a macro are scoped in the macro's module, not in
1270 ;; the expansion's module. Seems to work well.
1271 ;;
1272 ;; The only wrinkle is when we want a macro to expand to code in another
1273 ;; module, as is the case for the r6rs `library' form -- the body expressions
1274 ;; should be scoped relative the the new module, the one defined by the macro.
1275 ;; For that, use `(@@ mod-name body)'.
1276 ;;
1277 ;; Part of the macro output will be from the site of the macro use and part
1278 ;; from the macro definition. We allow source information from the macro use
1279 ;; to pass through, but we annotate the parts coming from the macro with the
1280 ;; source location information corresponding to the macro use. It would be
1281 ;; really nice if we could also annotate introduced expressions with the
1282 ;; locations corresponding to the macro definition, but that is not yet
1283 ;; possible.
1284 (define chi-macro
1285 (lambda (p e r w s rib mod)
1286 (define rebuild-macro-output
1287 (lambda (x m)
1288 (cond ((pair? x)
1289 (decorate-source
1290 (cons (rebuild-macro-output (car x) m)
1291 (rebuild-macro-output (cdr x) m))
1292 s))
1293 ((syntax-object? x)
1294 (let ((w (syntax-object-wrap x)))
1295 (let ((ms (wrap-marks w)) (s (wrap-subst w)))
1296 (if (and (pair? ms) (eq? (car ms) the-anti-mark))
1297 ;; output is from original text
1298 (make-syntax-object
1299 (syntax-object-expression x)
1300 (make-wrap (cdr ms) (if rib (cons rib (cdr s)) (cdr s)))
1301 (syntax-object-module x))
1302 ;; output introduced by macro
1303 (make-syntax-object
1304 (decorate-source (syntax-object-expression x) s)
1305 (make-wrap (cons m ms)
1306 (if rib
1307 (cons rib (cons 'shift s))
1308 (cons 'shift s)))
1309 (syntax-object-module x))))))
1310
1311 ((vector? x)
1312 (let* ((n (vector-length x))
1313 (v (decorate-source (make-vector n) x)))
1314 (do ((i 0 (fx+ i 1)))
1315 ((fx= i n) v)
1316 (vector-set! v i
1317 (rebuild-macro-output (vector-ref x i) m)))))
1318 ((symbol? x)
1319 (syntax-violation #f "encountered raw symbol in macro output"
1320 (source-wrap e w (wrap-subst w) mod) x))
1321 (else (decorate-source x s)))))
1322 (rebuild-macro-output (p (source-wrap e (anti-mark w) s mod))
1323 (new-mark))))
1324
1325 (define chi-body
1326 ;; In processing the forms of the body, we create a new, empty wrap.
1327 ;; This wrap is augmented (destructively) each time we discover that
1328 ;; the next form is a definition. This is done:
1329 ;;
1330 ;; (1) to allow the first nondefinition form to be a call to
1331 ;; one of the defined ids even if the id previously denoted a
1332 ;; definition keyword or keyword for a macro expanding into a
1333 ;; definition;
1334 ;; (2) to prevent subsequent definition forms (but unfortunately
1335 ;; not earlier ones) and the first nondefinition form from
1336 ;; confusing one of the bound identifiers for an auxiliary
1337 ;; keyword; and
1338 ;; (3) so that we do not need to restart the expansion of the
1339 ;; first nondefinition form, which is problematic anyway
1340 ;; since it might be the first element of a begin that we
1341 ;; have just spliced into the body (meaning if we restarted,
1342 ;; we'd really need to restart with the begin or the macro
1343 ;; call that expanded into the begin, and we'd have to give
1344 ;; up allowing (begin <defn>+ <expr>+), which is itself
1345 ;; problematic since we don't know if a begin contains only
1346 ;; definitions until we've expanded it).
1347 ;;
1348 ;; Before processing the body, we also create a new environment
1349 ;; containing a placeholder for the bindings we will add later and
1350 ;; associate this environment with each form. In processing a
1351 ;; let-syntax or letrec-syntax, the associated environment may be
1352 ;; augmented with local keyword bindings, so the environment may
1353 ;; be different for different forms in the body. Once we have
1354 ;; gathered up all of the definitions, we evaluate the transformer
1355 ;; expressions and splice into r at the placeholder the new variable
1356 ;; and keyword bindings. This allows let-syntax or letrec-syntax
1357 ;; forms local to a portion or all of the body to shadow the
1358 ;; definition bindings.
1359 ;;
1360 ;; Subforms of a begin, let-syntax, or letrec-syntax are spliced
1361 ;; into the body.
1362 ;;
1363 ;; outer-form is fully wrapped w/source
1364 (lambda (body outer-form r w mod)
1365 (let* ((r (cons '("placeholder" . (placeholder)) r))
1366 (ribcage (make-empty-ribcage))
1367 (w (make-wrap (wrap-marks w) (cons ribcage (wrap-subst w)))))
1368 (let parse ((body (map (lambda (x) (cons r (wrap x w mod))) body))
1369 (ids '()) (labels '())
1370 (var-ids '()) (vars '()) (vals '()) (bindings '()))
1371 (if (null? body)
1372 (syntax-violation #f "no expressions in body" outer-form)
1373 (let ((e (cdar body)) (er (caar body)))
1374 (call-with-values
1375 (lambda () (syntax-type e er empty-wrap (source-annotation er) ribcage mod #f))
1376 (lambda (type value e w s mod)
1377 (case type
1378 ((define-form)
1379 (let ((id (wrap value w mod)) (label (gen-label)))
1380 (let ((var (gen-var id)))
1381 (extend-ribcage! ribcage id label)
1382 (parse (cdr body)
1383 (cons id ids) (cons label labels)
1384 (cons id var-ids)
1385 (cons var vars) (cons (cons er (wrap e w mod)) vals)
1386 (cons (make-binding 'lexical var) bindings)))))
1387 ((define-syntax-form)
1388 (let ((id (wrap value w mod)) (label (gen-label)))
1389 (extend-ribcage! ribcage id label)
1390 (parse (cdr body)
1391 (cons id ids) (cons label labels)
1392 var-ids vars vals
1393 (cons (make-binding 'macro (cons er (wrap e w mod)))
1394 bindings))))
1395 ((begin-form)
1396 (syntax-case e ()
1397 ((_ e1 ...)
1398 (parse (let f ((forms #'(e1 ...)))
1399 (if (null? forms)
1400 (cdr body)
1401 (cons (cons er (wrap (car forms) w mod))
1402 (f (cdr forms)))))
1403 ids labels var-ids vars vals bindings))))
1404 ((local-syntax-form)
1405 (chi-local-syntax value e er w s mod
1406 (lambda (forms er w s mod)
1407 (parse (let f ((forms forms))
1408 (if (null? forms)
1409 (cdr body)
1410 (cons (cons er (wrap (car forms) w mod))
1411 (f (cdr forms)))))
1412 ids labels var-ids vars vals bindings))))
1413 (else ; found a non-definition
1414 (if (null? ids)
1415 (build-sequence no-source
1416 (map (lambda (x)
1417 (chi (cdr x) (car x) empty-wrap mod))
1418 (cons (cons er (source-wrap e w s mod))
1419 (cdr body))))
1420 (begin
1421 (if (not (valid-bound-ids? ids))
1422 (syntax-violation
1423 #f "invalid or duplicate identifier in definition"
1424 outer-form))
1425 (let loop ((bs bindings) (er-cache #f) (r-cache #f))
1426 (if (not (null? bs))
1427 (let* ((b (car bs)))
1428 (if (eq? (car b) 'macro)
1429 (let* ((er (cadr b))
1430 (r-cache
1431 (if (eq? er er-cache)
1432 r-cache
1433 (macros-only-env er))))
1434 (set-cdr! b
1435 (eval-local-transformer
1436 (chi (cddr b) r-cache empty-wrap mod)
1437 mod))
1438 (loop (cdr bs) er r-cache))
1439 (loop (cdr bs) er-cache r-cache)))))
1440 (set-cdr! r (extend-env labels bindings (cdr r)))
1441 (build-letrec no-source #t
1442 (reverse (map syntax->datum var-ids))
1443 (reverse vars)
1444 (map (lambda (x)
1445 (chi (cdr x) (car x) empty-wrap mod))
1446 (reverse vals))
1447 (build-sequence no-source
1448 (map (lambda (x)
1449 (chi (cdr x) (car x) empty-wrap mod))
1450 (cons (cons er (source-wrap e w s mod))
1451 (cdr body)))))))))))))))))
1452
1453 (define chi-local-syntax
1454 (lambda (rec? e r w s mod k)
1455 (syntax-case e ()
1456 ((_ ((id val) ...) e1 e2 ...)
1457 (let ((ids #'(id ...)))
1458 (if (not (valid-bound-ids? ids))
1459 (syntax-violation #f "duplicate bound keyword" e)
1460 (let ((labels (gen-labels ids)))
1461 (let ((new-w (make-binding-wrap ids labels w)))
1462 (k #'(e1 e2 ...)
1463 (extend-env
1464 labels
1465 (let ((w (if rec? new-w w))
1466 (trans-r (macros-only-env r)))
1467 (map (lambda (x)
1468 (make-binding 'macro
1469 (eval-local-transformer
1470 (chi x trans-r w mod)
1471 mod)))
1472 #'(val ...)))
1473 r)
1474 new-w
1475 s
1476 mod))))))
1477 (_ (syntax-violation #f "bad local syntax definition"
1478 (source-wrap e w s mod))))))
1479
1480 (define eval-local-transformer
1481 (lambda (expanded mod)
1482 (let ((p (local-eval-hook expanded mod)))
1483 (if (procedure? p)
1484 p
1485 (syntax-violation #f "nonprocedure transformer" p)))))
1486
1487 (define chi-void
1488 (lambda ()
1489 (build-void no-source)))
1490
1491 (define ellipsis?
1492 (lambda (x)
1493 (and (nonsymbol-id? x)
1494 (free-id=? x #'(... ...)))))
1495
1496 (define lambda-formals
1497 (lambda (orig-args)
1498 (define (req args rreq)
1499 (syntax-case args ()
1500 (()
1501 (check (reverse rreq) #f))
1502 ((a . b) (id? #'a)
1503 (req #'b (cons #'a rreq)))
1504 (r (id? #'r)
1505 (check (reverse rreq) #'r))
1506 (else
1507 (syntax-violation 'lambda "invalid argument list" orig-args args))))
1508 (define (check req rest)
1509 (cond
1510 ((distinct-bound-ids? (if rest (cons rest req) req))
1511 (values req #f rest #f))
1512 (else
1513 (syntax-violation 'lambda "duplicate identifier in argument list"
1514 orig-args))))
1515 (req orig-args '())))
1516
1517 (define chi-simple-lambda
1518 (lambda (e r w s mod req rest meta body)
1519 (let* ((ids (if rest (append req (list rest)) req))
1520 (vars (map gen-var ids))
1521 (labels (gen-labels ids)))
1522 (build-simple-lambda
1523 s
1524 (map syntax->datum req) (and rest (syntax->datum rest)) vars
1525 meta
1526 (chi-body body (source-wrap e w s mod)
1527 (extend-var-env labels vars r)
1528 (make-binding-wrap ids labels w)
1529 mod)))))
1530
1531 (define lambda*-formals
1532 (lambda (orig-args)
1533 (define (req args rreq)
1534 (syntax-case args ()
1535 (()
1536 (check (reverse rreq) '() #f '()))
1537 ((a . b) (id? #'a)
1538 (req #'b (cons #'a rreq)))
1539 ((a . b) (eq? (syntax->datum #'a) #:optional)
1540 (opt #'b (reverse rreq) '()))
1541 ((a . b) (eq? (syntax->datum #'a) #:key)
1542 (key #'b (reverse rreq) '() '()))
1543 ((a b) (eq? (syntax->datum #'a) #:rest)
1544 (rest #'b (reverse rreq) '() '()))
1545 (r (id? #'r)
1546 (rest #'r (reverse rreq) '() '()))
1547 (else
1548 (syntax-violation 'lambda* "invalid argument list" orig-args args))))
1549 (define (opt args req ropt)
1550 (syntax-case args ()
1551 (()
1552 (check req (reverse ropt) #f '()))
1553 ((a . b) (id? #'a)
1554 (opt #'b req (cons #'(a #f) ropt)))
1555 (((a init) . b) (id? #'a)
1556 (opt #'b req (cons #'(a init) ropt)))
1557 ((a . b) (eq? (syntax->datum #'a) #:key)
1558 (key #'b req (reverse ropt) '()))
1559 ((a b) (eq? (syntax->datum #'a) #:rest)
1560 (rest #'b req (reverse ropt) '()))
1561 (r (id? #'r)
1562 (rest #'r req (reverse ropt) '()))
1563 (else
1564 (syntax-violation 'lambda* "invalid optional argument list"
1565 orig-args args))))
1566 (define (key args req opt rkey)
1567 (syntax-case args ()
1568 (()
1569 (check req opt #f (cons #f (reverse rkey))))
1570 ((a . b) (id? #'a)
1571 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1572 (key #'b req opt (cons #'(k a #f) rkey))))
1573 (((a init) . b) (id? #'a)
1574 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1575 (key #'b req opt (cons #'(k a init) rkey))))
1576 (((a init k) . b) (and (id? #'a)
1577 (keyword? (syntax->datum #'k)))
1578 (key #'b req opt (cons #'(k a init) rkey)))
1579 ((aok) (eq? (syntax->datum #'aok) #:allow-other-keys)
1580 (check req opt #f (cons #t (reverse rkey))))
1581 ((aok a b) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1582 (eq? (syntax->datum #'a) #:rest))
1583 (rest #'b req opt (cons #t (reverse rkey))))
1584 ((aok . r) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1585 (id? #'r))
1586 (rest #'r req opt (cons #t (reverse rkey))))
1587 ((a b) (eq? (syntax->datum #'a) #:rest)
1588 (rest #'b req opt (cons #f (reverse rkey))))
1589 (r (id? #'r)
1590 (rest #'r req opt (cons #f (reverse rkey))))
1591 (else
1592 (syntax-violation 'lambda* "invalid keyword argument list"
1593 orig-args args))))
1594 (define (rest args req opt kw)
1595 (syntax-case args ()
1596 (r (id? #'r)
1597 (check req opt #'r kw))
1598 (else
1599 (syntax-violation 'lambda* "invalid rest argument"
1600 orig-args args))))
1601 (define (check req opt rest kw)
1602 (cond
1603 ((distinct-bound-ids?
1604 (append req (map car opt) (if rest (list rest) '())
1605 (if (pair? kw) (map cadr (cdr kw)) '())))
1606 (values req opt rest kw))
1607 (else
1608 (syntax-violation 'lambda* "duplicate identifier in argument list"
1609 orig-args))))
1610 (req orig-args '())))
1611
1612 (define chi-lambda-case
1613 (lambda (e r w s mod get-formals clauses)
1614 (define (expand-req req opt rest kw body)
1615 (let ((vars (map gen-var req))
1616 (labels (gen-labels req)))
1617 (let ((r* (extend-var-env labels vars r))
1618 (w* (make-binding-wrap req labels w)))
1619 (expand-opt (map syntax->datum req)
1620 opt rest kw body (reverse vars) r* w* '() '()))))
1621 (define (expand-opt req opt rest kw body vars r* w* out inits)
1622 (cond
1623 ((pair? opt)
1624 (syntax-case (car opt) ()
1625 ((id i)
1626 (let* ((v (gen-var #'id))
1627 (l (gen-labels (list v)))
1628 (r** (extend-var-env l (list v) r*))
1629 (w** (make-binding-wrap (list #'id) l w*)))
1630 (expand-opt req (cdr opt) rest kw body (cons v vars)
1631 r** w** (cons (syntax->datum #'id) out)
1632 (cons (chi #'i r* w* mod) inits))))))
1633 (rest
1634 (let* ((v (gen-var rest))
1635 (l (gen-labels (list v)))
1636 (r* (extend-var-env l (list v) r*))
1637 (w* (make-binding-wrap (list rest) l w*)))
1638 (expand-kw req (if (pair? out) (reverse out) #f)
1639 (syntax->datum rest)
1640 (if (pair? kw) (cdr kw) kw)
1641 body (cons v vars) r* w*
1642 (if (pair? kw) (car kw) #f)
1643 '() inits)))
1644 (else
1645 (expand-kw req (if (pair? out) (reverse out) #f) #f
1646 (if (pair? kw) (cdr kw) kw)
1647 body vars r* w*
1648 (if (pair? kw) (car kw) #f)
1649 '() inits))))
1650 (define (expand-kw req opt rest kw body vars r* w* aok out inits)
1651 (cond
1652 ((pair? kw)
1653 (syntax-case (car kw) ()
1654 ((k id i)
1655 (let* ((v (gen-var #'id))
1656 (l (gen-labels (list v)))
1657 (r** (extend-var-env l (list v) r*))
1658 (w** (make-binding-wrap (list #'id) l w*)))
1659 (expand-kw req opt rest (cdr kw) body (cons v vars)
1660 r** w** aok
1661 (cons (list (syntax->datum #'k)
1662 (syntax->datum #'id)
1663 v)
1664 out)
1665 (cons (chi #'i r* w* mod) inits))))))
1666 (else
1667 (expand-body req opt rest
1668 (if (or aok (pair? out)) (cons aok (reverse out)) #f)
1669 body (reverse vars) r* w* (reverse inits) '()))))
1670 (define (expand-body req opt rest kw body vars r* w* inits meta)
1671 (syntax-case body ()
1672 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
1673 (expand-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1674 (append meta
1675 `((documentation
1676 . ,(syntax->datum #'docstring))))))
1677 ((#((k . v) ...) e1 e2 ...)
1678 (expand-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1679 (append meta (syntax->datum #'((k . v) ...)))))
1680 ((e1 e2 ...)
1681 (values meta req opt rest kw inits vars
1682 (chi-body #'(e1 e2 ...) (source-wrap e w s mod)
1683 r* w* mod)))))
1684
1685 (syntax-case clauses ()
1686 (() (values '() #f))
1687 (((args e1 e2 ...) (args* e1* e2* ...) ...)
1688 (call-with-values (lambda () (get-formals #'args))
1689 (lambda (req opt rest kw)
1690 (call-with-values (lambda ()
1691 (expand-req req opt rest kw #'(e1 e2 ...)))
1692 (lambda (meta req opt rest kw inits vars body)
1693 (call-with-values
1694 (lambda ()
1695 (chi-lambda-case e r w s mod get-formals
1696 #'((args* e1* e2* ...) ...)))
1697 (lambda (meta* else*)
1698 (values
1699 (append meta meta*)
1700 (build-lambda-case s req opt rest kw inits vars
1701 body else*))))))))))))
1702
1703 ;; data
1704
1705 ;; strips syntax-objects down to top-wrap
1706 ;;
1707 ;; since only the head of a list is annotated by the reader, not each pair
1708 ;; in the spine, we also check for pairs whose cars are annotated in case
1709 ;; we've been passed the cdr of an annotated list
1710
1711 (define strip
1712 (lambda (x w)
1713 (if (top-marked? w)
1714 x
1715 (let f ((x x))
1716 (cond
1717 ((syntax-object? x)
1718 (strip (syntax-object-expression x) (syntax-object-wrap x)))
1719 ((pair? x)
1720 (let ((a (f (car x))) (d (f (cdr x))))
1721 (if (and (eq? a (car x)) (eq? d (cdr x)))
1722 x
1723 (cons a d))))
1724 ((vector? x)
1725 (let ((old (vector->list x)))
1726 (let ((new (map f old)))
1727 (if (and-map* eq? old new) x (list->vector new)))))
1728 (else x))))))
1729
1730 ;; lexical variables
1731
1732 (define gen-var
1733 (lambda (id)
1734 (let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
1735 (build-lexical-var no-source id))))
1736
1737 ;; appears to return a reversed list
1738 (define lambda-var-list
1739 (lambda (vars)
1740 (let lvl ((vars vars) (ls '()) (w empty-wrap))
1741 (cond
1742 ((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
1743 ((id? vars) (cons (wrap vars w #f) ls))
1744 ((null? vars) ls)
1745 ((syntax-object? vars)
1746 (lvl (syntax-object-expression vars)
1747 ls
1748 (join-wraps w (syntax-object-wrap vars))))
1749 ;; include anything else to be caught by subsequent error
1750 ;; checking
1751 (else (cons vars ls))))))
1752
1753 ;; core transformers
1754
1755 (global-extend 'local-syntax 'letrec-syntax #t)
1756 (global-extend 'local-syntax 'let-syntax #f)
1757
1758 (global-extend 'core 'fluid-let-syntax
1759 (lambda (e r w s mod)
1760 (syntax-case e ()
1761 ((_ ((var val) ...) e1 e2 ...)
1762 (valid-bound-ids? #'(var ...))
1763 (let ((names (map (lambda (x) (id-var-name x w)) #'(var ...))))
1764 (for-each
1765 (lambda (id n)
1766 (case (binding-type (lookup n r mod))
1767 ((displaced-lexical)
1768 (syntax-violation 'fluid-let-syntax
1769 "identifier out of context"
1770 e
1771 (source-wrap id w s mod)))))
1772 #'(var ...)
1773 names)
1774 (chi-body
1775 #'(e1 e2 ...)
1776 (source-wrap e w s mod)
1777 (extend-env
1778 names
1779 (let ((trans-r (macros-only-env r)))
1780 (map (lambda (x)
1781 (make-binding 'macro
1782 (eval-local-transformer (chi x trans-r w mod)
1783 mod)))
1784 #'(val ...)))
1785 r)
1786 w
1787 mod)))
1788 (_ (syntax-violation 'fluid-let-syntax "bad syntax"
1789 (source-wrap e w s mod))))))
1790
1791 (global-extend 'core 'quote
1792 (lambda (e r w s mod)
1793 (syntax-case e ()
1794 ((_ e) (build-data s (strip #'e w)))
1795 (_ (syntax-violation 'quote "bad syntax"
1796 (source-wrap e w s mod))))))
1797
1798 (global-extend 'core 'syntax
1799 (let ()
1800 (define gen-syntax
1801 (lambda (src e r maps ellipsis? mod)
1802 (if (id? e)
1803 (let ((label (id-var-name e empty-wrap)))
1804 ;; Mod does not matter, we are looking to see if
1805 ;; the id is lexical syntax.
1806 (let ((b (lookup label r mod)))
1807 (if (eq? (binding-type b) 'syntax)
1808 (call-with-values
1809 (lambda ()
1810 (let ((var.lev (binding-value b)))
1811 (gen-ref src (car var.lev) (cdr var.lev) maps)))
1812 (lambda (var maps) (values `(ref ,var) maps)))
1813 (if (ellipsis? e)
1814 (syntax-violation 'syntax "misplaced ellipsis" src)
1815 (values `(quote ,e) maps)))))
1816 (syntax-case e ()
1817 ((dots e)
1818 (ellipsis? #'dots)
1819 (gen-syntax src #'e r maps (lambda (x) #f) mod))
1820 ((x dots . y)
1821 ;; this could be about a dozen lines of code, except that we
1822 ;; choose to handle #'(x ... ...) forms
1823 (ellipsis? #'dots)
1824 (let f ((y #'y)
1825 (k (lambda (maps)
1826 (call-with-values
1827 (lambda ()
1828 (gen-syntax src #'x r
1829 (cons '() maps) ellipsis? mod))
1830 (lambda (x maps)
1831 (if (null? (car maps))
1832 (syntax-violation 'syntax "extra ellipsis"
1833 src)
1834 (values (gen-map x (car maps))
1835 (cdr maps))))))))
1836 (syntax-case y ()
1837 ((dots . y)
1838 (ellipsis? #'dots)
1839 (f #'y
1840 (lambda (maps)
1841 (call-with-values
1842 (lambda () (k (cons '() maps)))
1843 (lambda (x maps)
1844 (if (null? (car maps))
1845 (syntax-violation 'syntax "extra ellipsis" src)
1846 (values (gen-mappend x (car maps))
1847 (cdr maps))))))))
1848 (_ (call-with-values
1849 (lambda () (gen-syntax src y r maps ellipsis? mod))
1850 (lambda (y maps)
1851 (call-with-values
1852 (lambda () (k maps))
1853 (lambda (x maps)
1854 (values (gen-append x y) maps)))))))))
1855 ((x . y)
1856 (call-with-values
1857 (lambda () (gen-syntax src #'x r maps ellipsis? mod))
1858 (lambda (x maps)
1859 (call-with-values
1860 (lambda () (gen-syntax src #'y r maps ellipsis? mod))
1861 (lambda (y maps) (values (gen-cons x y) maps))))))
1862 (#(e1 e2 ...)
1863 (call-with-values
1864 (lambda ()
1865 (gen-syntax src #'(e1 e2 ...) r maps ellipsis? mod))
1866 (lambda (e maps) (values (gen-vector e) maps))))
1867 (_ (values `(quote ,e) maps))))))
1868
1869 (define gen-ref
1870 (lambda (src var level maps)
1871 (if (fx= level 0)
1872 (values var maps)
1873 (if (null? maps)
1874 (syntax-violation 'syntax "missing ellipsis" src)
1875 (call-with-values
1876 (lambda () (gen-ref src var (fx- level 1) (cdr maps)))
1877 (lambda (outer-var outer-maps)
1878 (let ((b (assq outer-var (car maps))))
1879 (if b
1880 (values (cdr b) maps)
1881 (let ((inner-var (gen-var 'tmp)))
1882 (values inner-var
1883 (cons (cons (cons outer-var inner-var)
1884 (car maps))
1885 outer-maps)))))))))))
1886
1887 (define gen-mappend
1888 (lambda (e map-env)
1889 `(apply (primitive append) ,(gen-map e map-env))))
1890
1891 (define gen-map
1892 (lambda (e map-env)
1893 (let ((formals (map cdr map-env))
1894 (actuals (map (lambda (x) `(ref ,(car x))) map-env)))
1895 (cond
1896 ((eq? (car e) 'ref)
1897 ;; identity map equivalence:
1898 ;; (map (lambda (x) x) y) == y
1899 (car actuals))
1900 ((and-map
1901 (lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
1902 (cdr e))
1903 ;; eta map equivalence:
1904 ;; (map (lambda (x ...) (f x ...)) y ...) == (map f y ...)
1905 `(map (primitive ,(car e))
1906 ,@(map (let ((r (map cons formals actuals)))
1907 (lambda (x) (cdr (assq (cadr x) r))))
1908 (cdr e))))
1909 (else `(map (lambda ,formals ,e) ,@actuals))))))
1910
1911 (define gen-cons
1912 (lambda (x y)
1913 (case (car y)
1914 ((quote)
1915 (if (eq? (car x) 'quote)
1916 `(quote (,(cadr x) . ,(cadr y)))
1917 (if (eq? (cadr y) '())
1918 `(list ,x)
1919 `(cons ,x ,y))))
1920 ((list) `(list ,x ,@(cdr y)))
1921 (else `(cons ,x ,y)))))
1922
1923 (define gen-append
1924 (lambda (x y)
1925 (if (equal? y '(quote ()))
1926 x
1927 `(append ,x ,y))))
1928
1929 (define gen-vector
1930 (lambda (x)
1931 (cond
1932 ((eq? (car x) 'list) `(vector ,@(cdr x)))
1933 ((eq? (car x) 'quote) `(quote #(,@(cadr x))))
1934 (else `(list->vector ,x)))))
1935
1936
1937 (define regen
1938 (lambda (x)
1939 (case (car x)
1940 ((ref) (build-lexical-reference 'value no-source (cadr x) (cadr x)))
1941 ((primitive) (build-primref no-source (cadr x)))
1942 ((quote) (build-data no-source (cadr x)))
1943 ((lambda)
1944 (if (list? (cadr x))
1945 (build-simple-lambda no-source (cadr x) #f (cadr x) '() (regen (caddr x)))
1946 (error "how did we get here" x)))
1947 (else (build-application no-source
1948 (build-primref no-source (car x))
1949 (map regen (cdr x)))))))
1950
1951 (lambda (e r w s mod)
1952 (let ((e (source-wrap e w s mod)))
1953 (syntax-case e ()
1954 ((_ x)
1955 (call-with-values
1956 (lambda () (gen-syntax e #'x r '() ellipsis? mod))
1957 (lambda (e maps) (regen e))))
1958 (_ (syntax-violation 'syntax "bad `syntax' form" e)))))))
1959
1960 (global-extend 'core 'lambda
1961 (lambda (e r w s mod)
1962 (syntax-case e ()
1963 ((_ args e1 e2 ...)
1964 (call-with-values (lambda () (lambda-formals #'args))
1965 (lambda (req opt rest kw)
1966 (let lp ((body #'(e1 e2 ...)) (meta '()))
1967 (syntax-case body ()
1968 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
1969 (lp #'(e1 e2 ...)
1970 (append meta
1971 `((documentation
1972 . ,(syntax->datum #'docstring))))))
1973 ((#((k . v) ...) e1 e2 ...)
1974 (lp #'(e1 e2 ...)
1975 (append meta (syntax->datum #'((k . v) ...)))))
1976 (_ (chi-simple-lambda e r w s mod req rest meta body)))))))
1977 (_ (syntax-violation 'lambda "bad lambda" e)))))
1978
1979 (global-extend 'core 'lambda*
1980 (lambda (e r w s mod)
1981 (syntax-case e ()
1982 ((_ args e1 e2 ...)
1983 (call-with-values
1984 (lambda ()
1985 (chi-lambda-case e r w s mod
1986 lambda*-formals #'((args e1 e2 ...))))
1987 (lambda (meta lcase)
1988 (build-case-lambda s meta lcase))))
1989 (_ (syntax-violation 'lambda "bad lambda*" e)))))
1990
1991 (global-extend 'core 'case-lambda
1992 (lambda (e r w s mod)
1993 (syntax-case e ()
1994 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
1995 (call-with-values
1996 (lambda ()
1997 (chi-lambda-case e r w s mod
1998 lambda-formals
1999 #'((args e1 e2 ...) (args* e1* e2* ...) ...)))
2000 (lambda (meta lcase)
2001 (build-case-lambda s meta lcase))))
2002 (_ (syntax-violation 'case-lambda "bad case-lambda" e)))))
2003
2004 (global-extend 'core 'case-lambda*
2005 (lambda (e r w s mod)
2006 (syntax-case e ()
2007 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
2008 (call-with-values
2009 (lambda ()
2010 (chi-lambda-case e r w s mod
2011 lambda*-formals
2012 #'((args e1 e2 ...) (args* e1* e2* ...) ...)))
2013 (lambda (meta lcase)
2014 (build-case-lambda s meta lcase))))
2015 (_ (syntax-violation 'case-lambda "bad case-lambda*" e)))))
2016
2017 (global-extend 'core 'let
2018 (let ()
2019 (define (chi-let e r w s mod constructor ids vals exps)
2020 (if (not (valid-bound-ids? ids))
2021 (syntax-violation 'let "duplicate bound variable" e)
2022 (let ((labels (gen-labels ids))
2023 (new-vars (map gen-var ids)))
2024 (let ((nw (make-binding-wrap ids labels w))
2025 (nr (extend-var-env labels new-vars r)))
2026 (constructor s
2027 (map syntax->datum ids)
2028 new-vars
2029 (map (lambda (x) (chi x r w mod)) vals)
2030 (chi-body exps (source-wrap e nw s mod)
2031 nr nw mod))))))
2032 (lambda (e r w s mod)
2033 (syntax-case e ()
2034 ((_ ((id val) ...) e1 e2 ...)
2035 (and-map id? #'(id ...))
2036 (chi-let e r w s mod
2037 build-let
2038 #'(id ...)
2039 #'(val ...)
2040 #'(e1 e2 ...)))
2041 ((_ f ((id val) ...) e1 e2 ...)
2042 (and (id? #'f) (and-map id? #'(id ...)))
2043 (chi-let e r w s mod
2044 build-named-let
2045 #'(f id ...)
2046 #'(val ...)
2047 #'(e1 e2 ...)))
2048 (_ (syntax-violation 'let "bad let" (source-wrap e w s mod)))))))
2049
2050
2051 (global-extend 'core 'letrec
2052 (lambda (e r w s mod)
2053 (syntax-case e ()
2054 ((_ ((id val) ...) e1 e2 ...)
2055 (and-map id? #'(id ...))
2056 (let ((ids #'(id ...)))
2057 (if (not (valid-bound-ids? ids))
2058 (syntax-violation 'letrec "duplicate bound variable" e)
2059 (let ((labels (gen-labels ids))
2060 (new-vars (map gen-var ids)))
2061 (let ((w (make-binding-wrap ids labels w))
2062 (r (extend-var-env labels new-vars r)))
2063 (build-letrec s #f
2064 (map syntax->datum ids)
2065 new-vars
2066 (map (lambda (x) (chi x r w mod)) #'(val ...))
2067 (chi-body #'(e1 e2 ...)
2068 (source-wrap e w s mod) r w mod)))))))
2069 (_ (syntax-violation 'letrec "bad letrec" (source-wrap e w s mod))))))
2070
2071
2072 (global-extend 'core 'letrec*
2073 (lambda (e r w s mod)
2074 (syntax-case e ()
2075 ((_ ((id val) ...) e1 e2 ...)
2076 (and-map id? #'(id ...))
2077 (let ((ids #'(id ...)))
2078 (if (not (valid-bound-ids? ids))
2079 (syntax-violation 'letrec* "duplicate bound variable" e)
2080 (let ((labels (gen-labels ids))
2081 (new-vars (map gen-var ids)))
2082 (let ((w (make-binding-wrap ids labels w))
2083 (r (extend-var-env labels new-vars r)))
2084 (build-letrec s #t
2085 (map syntax->datum ids)
2086 new-vars
2087 (map (lambda (x) (chi x r w mod)) #'(val ...))
2088 (chi-body #'(e1 e2 ...)
2089 (source-wrap e w s mod) r w mod)))))))
2090 (_ (syntax-violation 'letrec* "bad letrec*" (source-wrap e w s mod))))))
2091
2092
2093 (global-extend 'core 'set!
2094 (lambda (e r w s mod)
2095 (syntax-case e ()
2096 ((_ id val)
2097 (id? #'id)
2098 (let ((n (id-var-name #'id w))
2099 ;; Lookup id in its module
2100 (id-mod (if (syntax-object? #'id)
2101 (syntax-object-module #'id)
2102 mod)))
2103 (let ((b (lookup n r id-mod)))
2104 (case (binding-type b)
2105 ((lexical)
2106 (build-lexical-assignment s
2107 (syntax->datum #'id)
2108 (binding-value b)
2109 (chi #'val r w mod)))
2110 ((global)
2111 (build-global-assignment s n (chi #'val r w mod) id-mod))
2112 ((macro)
2113 (let ((p (binding-value b)))
2114 (if (procedure-property p 'variable-transformer)
2115 ;; As syntax-type does, call chi-macro with
2116 ;; the mod of the expression. Hmm.
2117 (chi (chi-macro p e r w s #f mod) r empty-wrap mod)
2118 (syntax-violation 'set! "not a variable transformer"
2119 (wrap e w mod)
2120 (wrap #'id w id-mod)))))
2121 ((displaced-lexical)
2122 (syntax-violation 'set! "identifier out of context"
2123 (wrap #'id w mod)))
2124 (else (syntax-violation 'set! "bad set!"
2125 (source-wrap e w s mod)))))))
2126 ((_ (head tail ...) val)
2127 (call-with-values
2128 (lambda () (syntax-type #'head r empty-wrap no-source #f mod #t))
2129 (lambda (type value ee ww ss modmod)
2130 (case type
2131 ((module-ref)
2132 (let ((val (chi #'val r w mod)))
2133 (call-with-values (lambda () (value #'(head tail ...) r w))
2134 (lambda (e r w s* mod)
2135 (syntax-case e ()
2136 (e (id? #'e)
2137 (build-global-assignment s (syntax->datum #'e)
2138 val mod)))))))
2139 (else
2140 (build-application s
2141 (chi #'(setter head) r w mod)
2142 (map (lambda (e) (chi e r w mod))
2143 #'(tail ... val))))))))
2144 (_ (syntax-violation 'set! "bad set!" (source-wrap e w s mod))))))
2145
2146 (global-extend 'module-ref '@
2147 (lambda (e r w)
2148 (syntax-case e ()
2149 ((_ (mod ...) id)
2150 (and (and-map id? #'(mod ...)) (id? #'id))
2151 (values (syntax->datum #'id) r w #f
2152 (syntax->datum
2153 #'(public mod ...)))))))
2154
2155 (global-extend 'module-ref '@@
2156 (lambda (e r w)
2157 (define remodulate
2158 (lambda (x mod)
2159 (cond ((pair? x)
2160 (cons (remodulate (car x) mod)
2161 (remodulate (cdr x) mod)))
2162 ((syntax-object? x)
2163 (make-syntax-object
2164 (remodulate (syntax-object-expression x) mod)
2165 (syntax-object-wrap x)
2166 ;; hither the remodulation
2167 mod))
2168 ((vector? x)
2169 (let* ((n (vector-length x)) (v (make-vector n)))
2170 (do ((i 0 (fx+ i 1)))
2171 ((fx= i n) v)
2172 (vector-set! v i (remodulate (vector-ref x i) mod)))))
2173 (else x))))
2174 (syntax-case e ()
2175 ((_ (mod ...) exp)
2176 (and-map id? #'(mod ...))
2177 (let ((mod (syntax->datum #'(private mod ...))))
2178 (values (remodulate #'exp mod)
2179 r w (source-annotation #'exp)
2180 mod))))))
2181
2182 (global-extend 'core 'if
2183 (lambda (e r w s mod)
2184 (syntax-case e ()
2185 ((_ test then)
2186 (build-conditional
2187 s
2188 (chi #'test r w mod)
2189 (chi #'then r w mod)
2190 (build-void no-source)))
2191 ((_ test then else)
2192 (build-conditional
2193 s
2194 (chi #'test r w mod)
2195 (chi #'then r w mod)
2196 (chi #'else r w mod))))))
2197
2198 (global-extend 'core 'with-fluids
2199 (lambda (e r w s mod)
2200 (syntax-case e ()
2201 ((_ ((fluid val) ...) b b* ...)
2202 (build-dynlet
2203 s
2204 (map (lambda (x) (chi x r w mod)) #'(fluid ...))
2205 (map (lambda (x) (chi x r w mod)) #'(val ...))
2206 (chi-body #'(b b* ...)
2207 (source-wrap e w s mod) r w mod))))))
2208
2209 (global-extend 'begin 'begin '())
2210
2211 (global-extend 'define 'define '())
2212
2213 (global-extend 'define-syntax 'define-syntax '())
2214
2215 (global-extend 'eval-when 'eval-when '())
2216
2217 (global-extend 'core 'syntax-case
2218 (let ()
2219 (define convert-pattern
2220 ;; accepts pattern & keys
2221 ;; returns $sc-dispatch pattern & ids
2222 (lambda (pattern keys)
2223 (define cvt*
2224 (lambda (p* n ids)
2225 (if (null? p*)
2226 (values '() ids)
2227 (call-with-values
2228 (lambda () (cvt* (cdr p*) n ids))
2229 (lambda (y ids)
2230 (call-with-values
2231 (lambda () (cvt (car p*) n ids))
2232 (lambda (x ids)
2233 (values (cons x y) ids))))))))
2234 (define cvt
2235 (lambda (p n ids)
2236 (if (id? p)
2237 (cond
2238 ((bound-id-member? p keys)
2239 (values (vector 'free-id p) ids))
2240 ((free-id=? p #'_)
2241 (values '_ ids))
2242 (else
2243 (values 'any (cons (cons p n) ids))))
2244 (syntax-case p ()
2245 ((x dots)
2246 (ellipsis? (syntax dots))
2247 (call-with-values
2248 (lambda () (cvt (syntax x) (fx+ n 1) ids))
2249 (lambda (p ids)
2250 (values (if (eq? p 'any) 'each-any (vector 'each p))
2251 ids))))
2252 ((x dots ys ...)
2253 (ellipsis? (syntax dots))
2254 (call-with-values
2255 (lambda () (cvt* (syntax (ys ...)) n ids))
2256 (lambda (ys ids)
2257 (call-with-values
2258 (lambda () (cvt (syntax x) (+ n 1) ids))
2259 (lambda (x ids)
2260 (values `#(each+ ,x ,(reverse ys) ()) ids))))))
2261 ((x . y)
2262 (call-with-values
2263 (lambda () (cvt (syntax y) n ids))
2264 (lambda (y ids)
2265 (call-with-values
2266 (lambda () (cvt (syntax x) n ids))
2267 (lambda (x ids)
2268 (values (cons x y) ids))))))
2269 (() (values '() ids))
2270 (#(x ...)
2271 (call-with-values
2272 (lambda () (cvt (syntax (x ...)) n ids))
2273 (lambda (p ids) (values (vector 'vector p) ids))))
2274 (x (values (vector 'atom (strip p empty-wrap)) ids))))))
2275 (cvt pattern 0 '())))
2276
2277 (define build-dispatch-call
2278 (lambda (pvars exp y r mod)
2279 (let ((ids (map car pvars)) (levels (map cdr pvars)))
2280 (let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
2281 (build-application no-source
2282 (build-primref no-source 'apply)
2283 (list (build-simple-lambda no-source (map syntax->datum ids) #f new-vars '()
2284 (chi exp
2285 (extend-env
2286 labels
2287 (map (lambda (var level)
2288 (make-binding 'syntax `(,var . ,level)))
2289 new-vars
2290 (map cdr pvars))
2291 r)
2292 (make-binding-wrap ids labels empty-wrap)
2293 mod))
2294 y))))))
2295
2296 (define gen-clause
2297 (lambda (x keys clauses r pat fender exp mod)
2298 (call-with-values
2299 (lambda () (convert-pattern pat keys))
2300 (lambda (p pvars)
2301 (cond
2302 ((not (distinct-bound-ids? (map car pvars)))
2303 (syntax-violation 'syntax-case "duplicate pattern variable" pat))
2304 ((not (and-map (lambda (x) (not (ellipsis? (car x)))) pvars))
2305 (syntax-violation 'syntax-case "misplaced ellipsis" pat))
2306 (else
2307 (let ((y (gen-var 'tmp)))
2308 ;; fat finger binding and references to temp variable y
2309 (build-application no-source
2310 (build-simple-lambda no-source (list 'tmp) #f (list y) '()
2311 (let ((y (build-lexical-reference 'value no-source
2312 'tmp y)))
2313 (build-conditional no-source
2314 (syntax-case fender ()
2315 (#t y)
2316 (_ (build-conditional no-source
2317 y
2318 (build-dispatch-call pvars fender y r mod)
2319 (build-data no-source #f))))
2320 (build-dispatch-call pvars exp y r mod)
2321 (gen-syntax-case x keys clauses r mod))))
2322 (list (if (eq? p 'any)
2323 (build-application no-source
2324 (build-primref no-source 'list)
2325 (list x))
2326 (build-application no-source
2327 (build-primref no-source '$sc-dispatch)
2328 (list x (build-data no-source p)))))))))))))
2329
2330 (define gen-syntax-case
2331 (lambda (x keys clauses r mod)
2332 (if (null? clauses)
2333 (build-application no-source
2334 (build-primref no-source 'syntax-violation)
2335 (list (build-data no-source #f)
2336 (build-data no-source
2337 "source expression failed to match any pattern")
2338 x))
2339 (syntax-case (car clauses) ()
2340 ((pat exp)
2341 (if (and (id? #'pat)
2342 (and-map (lambda (x) (not (free-id=? #'pat x)))
2343 (cons #'(... ...) keys)))
2344 (if (free-id=? #'pad #'_)
2345 (chi #'exp r empty-wrap mod)
2346 (let ((labels (list (gen-label)))
2347 (var (gen-var #'pat)))
2348 (build-application no-source
2349 (build-simple-lambda
2350 no-source (list (syntax->datum #'pat)) #f (list var)
2351 '()
2352 (chi #'exp
2353 (extend-env labels
2354 (list (make-binding 'syntax `(,var . 0)))
2355 r)
2356 (make-binding-wrap #'(pat)
2357 labels empty-wrap)
2358 mod))
2359 (list x))))
2360 (gen-clause x keys (cdr clauses) r
2361 #'pat #t #'exp mod)))
2362 ((pat fender exp)
2363 (gen-clause x keys (cdr clauses) r
2364 #'pat #'fender #'exp mod))
2365 (_ (syntax-violation 'syntax-case "invalid clause"
2366 (car clauses)))))))
2367
2368 (lambda (e r w s mod)
2369 (let ((e (source-wrap e w s mod)))
2370 (syntax-case e ()
2371 ((_ val (key ...) m ...)
2372 (if (and-map (lambda (x) (and (id? x) (not (ellipsis? x))))
2373 #'(key ...))
2374 (let ((x (gen-var 'tmp)))
2375 ;; fat finger binding and references to temp variable x
2376 (build-application s
2377 (build-simple-lambda no-source (list 'tmp) #f (list x) '()
2378 (gen-syntax-case (build-lexical-reference 'value no-source
2379 'tmp x)
2380 #'(key ...) #'(m ...)
2381 r
2382 mod))
2383 (list (chi #'val r empty-wrap mod))))
2384 (syntax-violation 'syntax-case "invalid literals list" e))))))))
2385
2386 ;; The portable macroexpand seeds chi-top's mode m with 'e (for
2387 ;; evaluating) and esew (which stands for "eval syntax expanders
2388 ;; when") with '(eval). In Chez Scheme, m is set to 'c instead of e
2389 ;; if we are compiling a file, and esew is set to
2390 ;; (eval-syntactic-expanders-when), which defaults to the list
2391 ;; '(compile load eval). This means that, by default, top-level
2392 ;; syntactic definitions are evaluated immediately after they are
2393 ;; expanded, and the expanded definitions are also residualized into
2394 ;; the object file if we are compiling a file.
2395 (set! macroexpand
2396 (lambda* (x #:optional (m 'e) (esew '(eval)))
2397 (chi-top-sequence (list x) null-env top-wrap #f m esew
2398 (cons 'hygiene (module-name (current-module))))))
2399
2400 (set! identifier?
2401 (lambda (x)
2402 (nonsymbol-id? x)))
2403
2404 (set! datum->syntax
2405 (lambda (id datum)
2406 (make-syntax-object datum (syntax-object-wrap id)
2407 (syntax-object-module id))))
2408
2409 (set! syntax->datum
2410 ;; accepts any object, since syntax objects may consist partially
2411 ;; or entirely of unwrapped, nonsymbolic data
2412 (lambda (x)
2413 (strip x empty-wrap)))
2414
2415 (set! syntax-source
2416 (lambda (x) (source-annotation x)))
2417
2418 (set! generate-temporaries
2419 (lambda (ls)
2420 (arg-check list? ls 'generate-temporaries)
2421 (map (lambda (x) (wrap (gensym-hook) top-wrap #f)) ls)))
2422
2423 (set! free-identifier=?
2424 (lambda (x y)
2425 (arg-check nonsymbol-id? x 'free-identifier=?)
2426 (arg-check nonsymbol-id? y 'free-identifier=?)
2427 (free-id=? x y)))
2428
2429 (set! bound-identifier=?
2430 (lambda (x y)
2431 (arg-check nonsymbol-id? x 'bound-identifier=?)
2432 (arg-check nonsymbol-id? y 'bound-identifier=?)
2433 (bound-id=? x y)))
2434
2435 (set! syntax-violation
2436 (lambda* (who message form #:optional subform)
2437 (arg-check (lambda (x) (or (not x) (string? x) (symbol? x)))
2438 who 'syntax-violation)
2439 (arg-check string? message 'syntax-violation)
2440 (throw 'syntax-error who message
2441 (source-annotation (or form subform))
2442 (strip form empty-wrap)
2443 (and subform (strip subform empty-wrap)))))
2444
2445 ;; $sc-dispatch expects an expression and a pattern. If the expression
2446 ;; matches the pattern a list of the matching expressions for each
2447 ;; "any" is returned. Otherwise, #f is returned. (This use of #f will
2448 ;; not work on r4rs implementations that violate the ieee requirement
2449 ;; that #f and () be distinct.)
2450
2451 ;; The expression is matched with the pattern as follows:
2452
2453 ;; pattern: matches:
2454 ;; () empty list
2455 ;; any anything
2456 ;; (<pattern>1 . <pattern>2) (<pattern>1 . <pattern>2)
2457 ;; each-any (any*)
2458 ;; #(free-id <key>) <key> with free-identifier=?
2459 ;; #(each <pattern>) (<pattern>*)
2460 ;; #(each+ p1 (p2_1 ... p2_n) p3) (p1* (p2_n ... p2_1) . p3)
2461 ;; #(vector <pattern>) (list->vector <pattern>)
2462 ;; #(atom <object>) <object> with "equal?"
2463
2464 ;; Vector cops out to pair under assumption that vectors are rare. If
2465 ;; not, should convert to:
2466 ;; #(vector <pattern>*) #(<pattern>*)
2467
2468 (let ()
2469
2470 (define match-each
2471 (lambda (e p w mod)
2472 (cond
2473 ((pair? e)
2474 (let ((first (match (car e) p w '() mod)))
2475 (and first
2476 (let ((rest (match-each (cdr e) p w mod)))
2477 (and rest (cons first rest))))))
2478 ((null? e) '())
2479 ((syntax-object? e)
2480 (match-each (syntax-object-expression e)
2481 p
2482 (join-wraps w (syntax-object-wrap e))
2483 (syntax-object-module e)))
2484 (else #f))))
2485
2486 (define match-each+
2487 (lambda (e x-pat y-pat z-pat w r mod)
2488 (let f ((e e) (w w))
2489 (cond
2490 ((pair? e)
2491 (call-with-values (lambda () (f (cdr e) w))
2492 (lambda (xr* y-pat r)
2493 (if r
2494 (if (null? y-pat)
2495 (let ((xr (match (car e) x-pat w '() mod)))
2496 (if xr
2497 (values (cons xr xr*) y-pat r)
2498 (values #f #f #f)))
2499 (values
2500 '()
2501 (cdr y-pat)
2502 (match (car e) (car y-pat) w r mod)))
2503 (values #f #f #f)))))
2504 ((syntax-object? e)
2505 (f (syntax-object-expression e) (join-wraps w e)))
2506 (else
2507 (values '() y-pat (match e z-pat w r mod)))))))
2508
2509 (define match-each-any
2510 (lambda (e w mod)
2511 (cond
2512 ((pair? e)
2513 (let ((l (match-each-any (cdr e) w mod)))
2514 (and l (cons (wrap (car e) w mod) l))))
2515 ((null? e) '())
2516 ((syntax-object? e)
2517 (match-each-any (syntax-object-expression e)
2518 (join-wraps w (syntax-object-wrap e))
2519 mod))
2520 (else #f))))
2521
2522 (define match-empty
2523 (lambda (p r)
2524 (cond
2525 ((null? p) r)
2526 ((eq? p '_) r)
2527 ((eq? p 'any) (cons '() r))
2528 ((pair? p) (match-empty (car p) (match-empty (cdr p) r)))
2529 ((eq? p 'each-any) (cons '() r))
2530 (else
2531 (case (vector-ref p 0)
2532 ((each) (match-empty (vector-ref p 1) r))
2533 ((each+) (match-empty (vector-ref p 1)
2534 (match-empty
2535 (reverse (vector-ref p 2))
2536 (match-empty (vector-ref p 3) r))))
2537 ((free-id atom) r)
2538 ((vector) (match-empty (vector-ref p 1) r)))))))
2539
2540 (define combine
2541 (lambda (r* r)
2542 (if (null? (car r*))
2543 r
2544 (cons (map car r*) (combine (map cdr r*) r)))))
2545
2546 (define match*
2547 (lambda (e p w r mod)
2548 (cond
2549 ((null? p) (and (null? e) r))
2550 ((pair? p)
2551 (and (pair? e) (match (car e) (car p) w
2552 (match (cdr e) (cdr p) w r mod)
2553 mod)))
2554 ((eq? p 'each-any)
2555 (let ((l (match-each-any e w mod))) (and l (cons l r))))
2556 (else
2557 (case (vector-ref p 0)
2558 ((each)
2559 (if (null? e)
2560 (match-empty (vector-ref p 1) r)
2561 (let ((l (match-each e (vector-ref p 1) w mod)))
2562 (and l
2563 (let collect ((l l))
2564 (if (null? (car l))
2565 r
2566 (cons (map car l) (collect (map cdr l)))))))))
2567 ((each+)
2568 (call-with-values
2569 (lambda ()
2570 (match-each+ e (vector-ref p 1) (vector-ref p 2) (vector-ref p 3) w r mod))
2571 (lambda (xr* y-pat r)
2572 (and r
2573 (null? y-pat)
2574 (if (null? xr*)
2575 (match-empty (vector-ref p 1) r)
2576 (combine xr* r))))))
2577 ((free-id) (and (id? e) (free-id=? (wrap e w mod) (vector-ref p 1)) r))
2578 ((atom) (and (equal? (vector-ref p 1) (strip e w)) r))
2579 ((vector)
2580 (and (vector? e)
2581 (match (vector->list e) (vector-ref p 1) w r mod))))))))
2582
2583 (define match
2584 (lambda (e p w r mod)
2585 (cond
2586 ((not r) #f)
2587 ((eq? p '_) r)
2588 ((eq? p 'any) (cons (wrap e w mod) r))
2589 ((syntax-object? e)
2590 (match*
2591 (syntax-object-expression e)
2592 p
2593 (join-wraps w (syntax-object-wrap e))
2594 r
2595 (syntax-object-module e)))
2596 (else (match* e p w r mod)))))
2597
2598 (set! $sc-dispatch
2599 (lambda (e p)
2600 (cond
2601 ((eq? p 'any) (list e))
2602 ((eq? p '_) '())
2603 ((syntax-object? e)
2604 (match* (syntax-object-expression e)
2605 p (syntax-object-wrap e) '() (syntax-object-module e)))
2606 (else (match* e p empty-wrap '() #f))))))))
2607
2608
2609 (define-syntax with-syntax
2610 (lambda (x)
2611 (syntax-case x ()
2612 ((_ () e1 e2 ...)
2613 #'(begin e1 e2 ...))
2614 ((_ ((out in)) e1 e2 ...)
2615 #'(syntax-case in () (out (begin e1 e2 ...))))
2616 ((_ ((out in) ...) e1 e2 ...)
2617 #'(syntax-case (list in ...) ()
2618 ((out ...) (begin e1 e2 ...)))))))
2619
2620 (define-syntax syntax-rules
2621 (lambda (x)
2622 (syntax-case x ()
2623 ((_ (k ...) ((keyword . pattern) template) ...)
2624 #'(lambda (x)
2625 ;; embed patterns as procedure metadata
2626 #((macro-type . syntax-rules)
2627 (patterns pattern ...))
2628 (syntax-case x (k ...)
2629 ((dummy . pattern) #'template)
2630 ...)))
2631 ((_ (k ...) docstring ((keyword . pattern) template) ...)
2632 (string? (syntax->datum #'docstring))
2633 #'(lambda (x)
2634 ;; the same, but allow a docstring
2635 docstring
2636 #((macro-type . syntax-rules)
2637 (patterns pattern ...))
2638 (syntax-case x (k ...)
2639 ((dummy . pattern) #'template)
2640 ...))))))
2641
2642 (define-syntax let*
2643 (lambda (x)
2644 (syntax-case x ()
2645 ((let* ((x v) ...) e1 e2 ...)
2646 (and-map identifier? #'(x ...))
2647 (let f ((bindings #'((x v) ...)))
2648 (if (null? bindings)
2649 #'(let () e1 e2 ...)
2650 (with-syntax ((body (f (cdr bindings)))
2651 (binding (car bindings)))
2652 #'(let (binding) body))))))))
2653
2654 (define-syntax do
2655 (lambda (orig-x)
2656 (syntax-case orig-x ()
2657 ((_ ((var init . step) ...) (e0 e1 ...) c ...)
2658 (with-syntax (((step ...)
2659 (map (lambda (v s)
2660 (syntax-case s ()
2661 (() v)
2662 ((e) #'e)
2663 (_ (syntax-violation
2664 'do "bad step expression"
2665 orig-x s))))
2666 #'(var ...)
2667 #'(step ...))))
2668 (syntax-case #'(e1 ...) ()
2669 (() #'(let doloop ((var init) ...)
2670 (if (not e0)
2671 (begin c ... (doloop step ...)))))
2672 ((e1 e2 ...)
2673 #'(let doloop ((var init) ...)
2674 (if e0
2675 (begin e1 e2 ...)
2676 (begin c ... (doloop step ...)))))))))))
2677
2678 (define-syntax quasiquote
2679 (let ()
2680 (define (quasi p lev)
2681 (syntax-case p (unquote quasiquote)
2682 ((unquote p)
2683 (if (= lev 0)
2684 #'("value" p)
2685 (quasicons #'("quote" unquote) (quasi #'(p) (- lev 1)))))
2686 ((quasiquote p) (quasicons #'("quote" quasiquote) (quasi #'(p) (+ lev 1))))
2687 ((p . q)
2688 (syntax-case #'p (unquote unquote-splicing)
2689 ((unquote p ...)
2690 (if (= lev 0)
2691 (quasilist* #'(("value" p) ...) (quasi #'q lev))
2692 (quasicons
2693 (quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
2694 (quasi #'q lev))))
2695 ((unquote-splicing p ...)
2696 (if (= lev 0)
2697 (quasiappend #'(("value" p) ...) (quasi #'q lev))
2698 (quasicons
2699 (quasicons #'("quote" unquote-splicing) (quasi #'(p ...) (- lev 1)))
2700 (quasi #'q lev))))
2701 (_ (quasicons (quasi #'p lev) (quasi #'q lev)))))
2702 (#(x ...) (quasivector (vquasi #'(x ...) lev)))
2703 (p #'("quote" p))))
2704 (define (vquasi p lev)
2705 (syntax-case p ()
2706 ((p . q)
2707 (syntax-case #'p (unquote unquote-splicing)
2708 ((unquote p ...)
2709 (if (= lev 0)
2710 (quasilist* #'(("value" p) ...) (vquasi #'q lev))
2711 (quasicons
2712 (quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
2713 (vquasi #'q lev))))
2714 ((unquote-splicing p ...)
2715 (if (= lev 0)
2716 (quasiappend #'(("value" p) ...) (vquasi #'q lev))
2717 (quasicons
2718 (quasicons
2719 #'("quote" unquote-splicing)
2720 (quasi #'(p ...) (- lev 1)))
2721 (vquasi #'q lev))))
2722 (_ (quasicons (quasi #'p lev) (vquasi #'q lev)))))
2723 (() #'("quote" ()))))
2724 (define (quasicons x y)
2725 (with-syntax ((x x) (y y))
2726 (syntax-case #'y ()
2727 (("quote" dy)
2728 (syntax-case #'x ()
2729 (("quote" dx) #'("quote" (dx . dy)))
2730 (_ (if (null? #'dy) #'("list" x) #'("list*" x y)))))
2731 (("list" . stuff) #'("list" x . stuff))
2732 (("list*" . stuff) #'("list*" x . stuff))
2733 (_ #'("list*" x y)))))
2734 (define (quasiappend x y)
2735 (syntax-case y ()
2736 (("quote" ())
2737 (cond
2738 ((null? x) #'("quote" ()))
2739 ((null? (cdr x)) (car x))
2740 (else (with-syntax (((p ...) x)) #'("append" p ...)))))
2741 (_
2742 (cond
2743 ((null? x) y)
2744 (else (with-syntax (((p ...) x) (y y)) #'("append" p ... y)))))))
2745 (define (quasilist* x y)
2746 (let f ((x x))
2747 (if (null? x)
2748 y
2749 (quasicons (car x) (f (cdr x))))))
2750 (define (quasivector x)
2751 (syntax-case x ()
2752 (("quote" (x ...)) #'("quote" #(x ...)))
2753 (_
2754 (let f ((y x) (k (lambda (ls) #`("vector" #,@ls))))
2755 (syntax-case y ()
2756 (("quote" (y ...)) (k #'(("quote" y) ...)))
2757 (("list" y ...) (k #'(y ...)))
2758 (("list*" y ... z) (f #'z (lambda (ls) (k (append #'(y ...) ls)))))
2759 (else #`("list->vector" #,x)))))))
2760 (define (emit x)
2761 (syntax-case x ()
2762 (("quote" x) #''x)
2763 (("list" x ...) #`(list #,@(map emit #'(x ...))))
2764 ;; could emit list* for 3+ arguments if implementation supports
2765 ;; list*
2766 (("list*" x ... y)
2767 (let f ((x* #'(x ...)))
2768 (if (null? x*)
2769 (emit #'y)
2770 #`(cons #,(emit (car x*)) #,(f (cdr x*))))))
2771 (("append" x ...) #`(append #,@(map emit #'(x ...))))
2772 (("vector" x ...) #`(vector #,@(map emit #'(x ...))))
2773 (("list->vector" x) #`(list->vector #,(emit #'x)))
2774 (("value" x) #'x)))
2775 (lambda (x)
2776 (syntax-case x ()
2777 ;; convert to intermediate language, combining introduced (but
2778 ;; not unquoted source) quote expressions where possible and
2779 ;; choosing optimal construction code otherwise, then emit
2780 ;; Scheme code corresponding to the intermediate language forms.
2781 ((_ e) (emit (quasi #'e 0)))))))
2782
2783 (define-syntax include
2784 (lambda (x)
2785 (define read-file
2786 (lambda (fn k)
2787 (let ((p (open-input-file fn)))
2788 (let f ((x (read p))
2789 (result '()))
2790 (if (eof-object? x)
2791 (begin
2792 (close-input-port p)
2793 (reverse result))
2794 (f (read p)
2795 (cons (datum->syntax k x) result)))))))
2796 (syntax-case x ()
2797 ((k filename)
2798 (let ((fn (syntax->datum #'filename)))
2799 (with-syntax (((exp ...) (read-file fn #'filename)))
2800 #'(begin exp ...)))))))
2801
2802 (define-syntax include-from-path
2803 (lambda (x)
2804 (syntax-case x ()
2805 ((k filename)
2806 (let ((fn (syntax->datum #'filename)))
2807 (with-syntax ((fn (datum->syntax
2808 #'filename
2809 (or (%search-load-path fn)
2810 (syntax-violation 'include-from-path
2811 "file not found in path"
2812 x #'filename)))))
2813 #'(include fn)))))))
2814
2815 (define-syntax unquote
2816 (lambda (x)
2817 (syntax-violation 'unquote
2818 "expression not valid outside of quasiquote"
2819 x)))
2820
2821 (define-syntax unquote-splicing
2822 (lambda (x)
2823 (syntax-violation 'unquote-splicing
2824 "expression not valid outside of quasiquote"
2825 x)))
2826
2827 (define-syntax case
2828 (lambda (x)
2829 (syntax-case x ()
2830 ((_ e m1 m2 ...)
2831 (with-syntax
2832 ((body (let f ((clause #'m1) (clauses #'(m2 ...)))
2833 (if (null? clauses)
2834 (syntax-case clause (else)
2835 ((else e1 e2 ...) #'(begin e1 e2 ...))
2836 (((k ...) e1 e2 ...)
2837 #'(if (memv t '(k ...)) (begin e1 e2 ...)))
2838 (_ (syntax-violation 'case "bad clause" x clause)))
2839 (with-syntax ((rest (f (car clauses) (cdr clauses))))
2840 (syntax-case clause (else)
2841 (((k ...) e1 e2 ...)
2842 #'(if (memv t '(k ...))
2843 (begin e1 e2 ...)
2844 rest))
2845 (_ (syntax-violation 'case "bad clause" x
2846 clause))))))))
2847 #'(let ((t e)) body))))))
2848
2849 (define (make-variable-transformer proc)
2850 (if (procedure? proc)
2851 (let ((trans (lambda (x)
2852 #((macro-type . variable-transformer))
2853 (proc x))))
2854 (set-procedure-property! trans 'variable-transformer #t)
2855 trans)
2856 (error "variable transformer not a procedure" proc)))
2857
2858 (define-syntax identifier-syntax
2859 (lambda (x)
2860 (syntax-case x (set!)
2861 ((_ e)
2862 #'(lambda (x)
2863 #((macro-type . identifier-syntax))
2864 (syntax-case x ()
2865 (id
2866 (identifier? #'id)
2867 #'e)
2868 ((_ x (... ...))
2869 #'(e x (... ...))))))
2870 ((_ (id exp1) ((set! var val) exp2))
2871 (and (identifier? #'id) (identifier? #'var))
2872 #'(make-variable-transformer
2873 (lambda (x)
2874 #((macro-type . variable-transformer))
2875 (syntax-case x (set!)
2876 ((set! var val) #'exp2)
2877 ((id x (... ...)) #'(exp1 x (... ...)))
2878 (id (identifier? #'id) #'exp1))))))))
2879
2880 (define-syntax define*
2881 (lambda (x)
2882 (syntax-case x ()
2883 ((_ (id . args) b0 b1 ...)
2884 #'(define id (lambda* args b0 b1 ...)))
2885 ((_ id val) (identifier? #'x)
2886 #'(define id val)))))