3 ;;;; Copyright (C) 2001, 2003, 2006, 2009, 2010, 2011,
4 ;;;; 2012, 2013 Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 3 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 ;;; Portable implementation of syntax-case
23 ;;; Originally extracted from Chez Scheme Version 5.9f
24 ;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
26 ;;; Copyright (c) 1992-1997 Cadence Research Systems
27 ;;; Permission to copy this software, in whole or in part, to use this
28 ;;; software for any lawful purpose, and to redistribute this software
29 ;;; is granted subject to the restriction that all copies made of this
30 ;;; software must include this copyright notice in full. This software
31 ;;; is provided AS IS, with NO WARRANTY, EITHER EXPRESS OR IMPLIED,
32 ;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
33 ;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
34 ;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
35 ;;; NATURE WHATSOEVER.
37 ;;; Modified by Mikael Djurfeldt <djurfeldt@nada.kth.se> according
38 ;;; to the ChangeLog distributed in the same directory as this file:
39 ;;; 1997-08-19, 1997-09-03, 1997-09-10, 2000-08-13, 2000-08-24,
40 ;;; 2000-09-12, 2001-03-08
42 ;;; Modified by Andy Wingo <wingo@pobox.com> according to the Git
43 ;;; revision control logs corresponding to this file: 2009, 2010.
46 ;;; This file defines the syntax-case expander, macroexpand, and a set
47 ;;; of associated syntactic forms and procedures. Of these, the
48 ;;; following are documented in The Scheme Programming Language,
49 ;;; Fourth Edition (R. Kent Dybvig, MIT Press, 2009), and in the
52 ;;; bound-identifier=?
55 ;;; syntax-parameterize
57 ;;; generate-temporaries
68 ;;; Additionally, the expander provides definitions for a number of core
69 ;;; Scheme syntactic bindings, such as `let', `lambda', and the like.
71 ;;; The remaining exports are listed below:
73 ;;; (macroexpand datum)
74 ;;; if datum represents a valid expression, macroexpand returns an
75 ;;; expanded version of datum in a core language that includes no
76 ;;; syntactic abstractions. The core language includes begin,
77 ;;; define, if, lambda, letrec, quote, and set!.
78 ;;; (eval-when situations expr ...)
79 ;;; conditionally evaluates expr ... at compile-time or run-time
80 ;;; depending upon situations (see the Chez Scheme System Manual,
81 ;;; Revision 3, for a complete description)
82 ;;; (syntax-violation who message form [subform])
83 ;;; used to report errors found during expansion
84 ;;; ($sc-dispatch e p)
85 ;;; used by expanded code to handle syntax-case matching
87 ;;; This file is shipped along with an expanded version of itself,
88 ;;; psyntax-pp.scm, which is loaded when psyntax.scm has not yet been
89 ;;; compiled. In this way, psyntax bootstraps off of an expanded
90 ;;; version of itself.
92 ;;; This implementation of the expander sometimes uses syntactic
93 ;;; abstractions when procedural abstractions would suffice. For
94 ;;; example, we define top-wrap and top-marked? as
96 ;;; (define-syntax top-wrap (identifier-syntax '((top))))
97 ;;; (define-syntax top-marked?
99 ;;; ((_ w) (memq 'top (wrap-marks w)))))
103 ;;; (define top-wrap '((top)))
104 ;;; (define top-marked?
105 ;;; (lambda (w) (memq 'top (wrap-marks w))))
107 ;;; On the other hand, we don't do this consistently; we define
108 ;;; make-wrap, wrap-marks, and wrap-subst simply as
110 ;;; (define make-wrap cons)
111 ;;; (define wrap-marks car)
112 ;;; (define wrap-subst cdr)
114 ;;; In Chez Scheme, the syntactic and procedural forms of these
115 ;;; abstractions are equivalent, since the optimizer consistently
116 ;;; integrates constants and small procedures. This will be true of
117 ;;; Guile as well, once we implement a proper inliner.
120 ;;; Implementation notes:
122 ;;; Objects with no standard print syntax, including objects containing
123 ;;; cycles and syntax object, are allowed in quoted data as long as they
124 ;;; are contained within a syntax form or produced by datum->syntax.
125 ;;; Such objects are never copied.
127 ;;; All identifiers that don't have macro definitions and are not bound
128 ;;; lexically are assumed to be global variables.
130 ;;; Top-level definitions of macro-introduced identifiers are allowed.
131 ;;; This may not be appropriate for implementations in which the
132 ;;; model is that bindings are created by definitions, as opposed to
133 ;;; one in which initial values are assigned by definitions.
135 ;;; Identifiers and syntax objects are implemented as vectors for
136 ;;; portability. As a result, it is possible to "forge" syntax objects.
138 ;;; The implementation of generate-temporaries assumes that it is
139 ;;; possible to generate globally unique symbols (gensyms).
141 ;;; The source location associated with incoming expressions is tracked
142 ;;; via the source-properties mechanism, a weak map from expression to
143 ;;; source information. At times the source is separated from the
144 ;;; expression; see the note below about "efficiency and confusion".
149 ;;; When changing syntax-object representations, it is necessary to support
150 ;;; both old and new syntax-object representations in id-var-name. It
151 ;;; should be sufficient to recognize old representations and treat
152 ;;; them as not lexically bound.
157 (set-current-module (resolve-module '(guile))))
160 (define-syntax define-expansion-constructors
164 (let lp ((n 0) (out '()))
165 (if (< n (vector-length %expanded-vtables))
167 (let* ((vtable (vector-ref %expanded-vtables n))
168 (stem (struct-ref vtable (+ vtable-offset-user 0)))
169 (fields (struct-ref vtable (+ vtable-offset-user 2)))
170 (sfields (map (lambda (f) (datum->syntax x f)) fields))
171 (ctor (datum->syntax x (symbol-append 'make- stem))))
172 (cons #`(define (#,ctor #,@sfields)
173 (make-struct (vector-ref %expanded-vtables #,n) 0
176 #`(begin #,@(reverse out))))))))
178 (define-syntax define-expansion-accessors
183 (let ((vtable (vector-ref %expanded-vtables n))
184 (stem (syntax->datum #'stem)))
185 (if (eq? (struct-ref vtable (+ vtable-offset-user 0)) stem)
187 (define (#,(datum->syntax x (symbol-append stem '?)) x)
189 (eq? (struct-vtable x)
190 (vector-ref %expanded-vtables #,n))))
193 (let ((get (datum->syntax x (symbol-append stem '- f)))
194 (set (datum->syntax x (symbol-append 'set- stem '- f '!)))
195 (idx (list-index (struct-ref vtable
196 (+ vtable-offset-user 2))
200 (struct-ref x #,idx))
202 (struct-set! x #,idx v)))))
203 (syntax->datum #'(field ...))))
206 (define-syntax define-structure
208 (define construct-name
209 (lambda (template-identifier . args)
217 (symbol->string (syntax->datum x))))
221 (and-map identifier? #'(name id1 ...))
223 ((constructor (construct-name #'name "make-" #'name))
224 (predicate (construct-name #'name #'name "?"))
226 (map (lambda (x) (construct-name x #'name "-" x))
230 (construct-name x "set-" #'name "-" x "!"))
233 (+ (length #'(id1 ...)) 1))
235 (let f ((i 1) (ids #'(id1 ...)))
238 (cons i (f (+ i 1) (cdr ids)))))))
242 (vector 'name id1 ... )))
246 (= (vector-length x) structure-length)
247 (eq? (vector-ref x 0) 'name))))
250 (vector-ref x index)))
254 (vector-set! x index update)))
258 (define-expansion-constructors)
259 (define-expansion-accessors lambda meta)
261 ;; hooks to nonportable run-time helpers
263 (define-syntax fx+ (identifier-syntax +))
264 (define-syntax fx- (identifier-syntax -))
265 (define-syntax fx= (identifier-syntax =))
266 (define-syntax fx< (identifier-syntax <))
268 (define top-level-eval-hook
272 (define local-eval-hook
276 ;; Capture syntax-session-id before we shove it off into a module.
278 (let ((v (module-variable (current-module) 'syntax-session-id)))
280 ((variable-ref v)))))
282 (define put-global-definition-hook
283 (lambda (symbol type val)
284 (module-define! (current-module)
286 (make-syntax-transformer symbol type val))))
288 (define get-global-definition-hook
289 (lambda (symbol module)
290 (if (and (not module) (current-module))
291 (warn "module system is booted, we should have a module" symbol))
292 (and (not (equal? module '(primitive)))
293 (let ((v (module-variable (if module
294 (resolve-module (cdr module))
297 (and v (variable-bound? v)
298 (let ((val (variable-ref v)))
299 (and (macro? val) (macro-type val)
300 (cons (macro-type val)
301 (macro-binding val))))))))))
304 (define (decorate-source e s)
305 (if (and s (supports-source-properties? e))
306 (set-source-properties! e s))
309 (define (maybe-name-value! name val)
311 (let ((meta (lambda-meta val)))
312 (if (not (assq 'name meta))
313 (set-lambda-meta! val (acons 'name name meta))))))
315 ;; output constructors
321 (lambda (source fun-exp arg-exps)
322 (make-call source fun-exp arg-exps)))
324 (define build-conditional
325 (lambda (source test-exp then-exp else-exp)
326 (make-conditional source test-exp then-exp else-exp)))
328 (define build-lexical-reference
329 (lambda (type source name var)
330 (make-lexical-ref source name var)))
332 (define build-lexical-assignment
333 (lambda (source name var exp)
334 (maybe-name-value! name exp)
335 (make-lexical-set source name var exp)))
337 (define (analyze-variable mod var modref-cont bare-cont)
340 (let ((kind (car mod))
343 ((public) (modref-cont mod var #t))
344 ((private) (if (not (equal? mod (module-name (current-module))))
345 (modref-cont mod var #f)
347 ((bare) (bare-cont var))
348 ((hygiene) (if (and (not (equal? mod (module-name (current-module))))
349 (module-variable (resolve-module mod) var))
350 (modref-cont mod var #f)
353 (syntax-violation #f "primitive not in operator position" var))
354 (else (syntax-violation #f "bad module kind" var mod))))))
356 (define build-global-reference
357 (lambda (source var mod)
360 (lambda (mod var public?)
361 (make-module-ref source mod var public?))
363 (make-toplevel-ref source var)))))
365 (define build-global-assignment
366 (lambda (source var exp mod)
367 (maybe-name-value! var exp)
370 (lambda (mod var public?)
371 (make-module-set source mod var public? exp))
373 (make-toplevel-set source var exp)))))
375 (define build-global-definition
376 (lambda (source var exp)
377 (maybe-name-value! var exp)
378 (make-toplevel-define source var exp)))
380 (define build-simple-lambda
381 (lambda (src req rest vars meta exp)
384 ;; hah, a case in which kwargs would be nice.
386 ;; src req opt rest kw inits vars body else
387 src req #f rest #f '() vars exp #f))))
389 (define build-case-lambda
390 (lambda (src meta body)
391 (make-lambda src meta body)))
393 (define build-lambda-case
395 ;; opt := (name ...) | #f
397 ;; kw := (allow-other-keys? (keyword name var) ...) | #f
400 ;; vars map to named arguments in the following order:
401 ;; required, optional (positional), rest, keyword.
402 ;; the body of a lambda: anything, already expanded
403 ;; else: lambda-case | #f
404 (lambda (src req opt rest kw inits vars body else-case)
405 (make-lambda-case src req opt rest kw inits vars body else-case)))
407 (define build-primcall
408 (lambda (src name args)
409 (make-primcall src name args)))
411 (define build-primref
413 (make-primitive-ref src name)))
415 (define (build-data src exp)
416 (make-const src exp))
418 (define build-sequence
420 (if (null? (cdr exps))
422 (make-seq src (car exps) (build-sequence #f (cdr exps))))))
425 (lambda (src ids vars val-exps body-exp)
426 (for-each maybe-name-value! ids val-exps)
429 (make-let src ids vars val-exps body-exp))))
431 (define build-named-let
432 (lambda (src ids vars val-exps body-exp)
437 (let ((proc (build-simple-lambda src ids #f vars '() body-exp)))
438 (maybe-name-value! f-name proc)
439 (for-each maybe-name-value! ids val-exps)
442 (list f-name) (list f) (list proc)
443 (build-call src (build-lexical-reference 'fun src f-name f)
447 (lambda (src in-order? ids vars val-exps body-exp)
451 (for-each maybe-name-value! ids val-exps)
452 (make-letrec src in-order? ids vars val-exps body-exp)))))
455 ;; FIXME: use a faster gensym
456 (define-syntax-rule (build-lexical-var src id)
457 (gensym (string-append (symbol->string id) "-")))
459 (define-structure (syntax-object expression wrap module))
461 (define-syntax no-source (identifier-syntax #f))
463 (define source-annotation
465 (let ((props (source-properties
466 (if (syntax-object? x)
467 (syntax-object-expression x)
469 (and (pair? props) props))))
471 (define-syntax-rule (arg-check pred? e who)
473 (if (not (pred? x)) (syntax-violation who "invalid argument" x))))
475 ;; compile-time environments
477 ;; wrap and environment comprise two level mapping.
478 ;; wrap : id --> label
479 ;; env : label --> <element>
481 ;; environments are represented in two parts: a lexical part and a global
482 ;; part. The lexical part is a simple list of associations from labels
483 ;; to bindings. The global part is implemented by
484 ;; {put,get}-global-definition-hook and associates symbols with
487 ;; global (assumed global variable) and displaced-lexical (see below)
488 ;; do not show up in any environment; instead, they are fabricated by
489 ;; resolve-identifier when it finds no other bindings.
491 ;; <environment> ::= ((<label> . <binding>)*)
493 ;; identifier bindings include a type and a value
495 ;; <binding> ::= (macro . <procedure>) macros
496 ;; (syntax-parameter . (<procedure>)) syntax parameters
497 ;; (core . <procedure>) core forms
498 ;; (module-ref . <procedure>) @ or @@
501 ;; (define-syntax) define-syntax
502 ;; (define-syntax-parameter) define-syntax-parameter
503 ;; (local-syntax . rec?) let-syntax/letrec-syntax
504 ;; (eval-when) eval-when
505 ;; (syntax . (<var> . <level>)) pattern variables
506 ;; (global) assumed global variable
507 ;; (lexical . <var>) lexical variables
508 ;; (displaced-lexical) displaced lexicals
509 ;; <level> ::= <nonnegative integer>
510 ;; <var> ::= variable returned by build-lexical-var
512 ;; a macro is a user-defined syntactic-form. a core is a
513 ;; system-defined syntactic form. begin, define, define-syntax,
514 ;; define-syntax-parameter, and eval-when are treated specially
515 ;; since they are sensitive to whether the form is at top-level and
516 ;; (except for eval-when) can denote valid internal definitions.
518 ;; a pattern variable is a variable introduced by syntax-case and can
519 ;; be referenced only within a syntax form.
521 ;; any identifier for which no top-level syntax definition or local
522 ;; binding of any kind has been seen is assumed to be a global
525 ;; a lexical variable is a lambda- or letrec-bound variable.
527 ;; a displaced-lexical identifier is a lexical identifier removed from
528 ;; it's scope by the return of a syntax object containing the identifier.
529 ;; a displaced lexical can also appear when a letrec-syntax-bound
530 ;; keyword is referenced on the rhs of one of the letrec-syntax clauses.
531 ;; a displaced lexical should never occur with properly written macros.
533 (define-syntax make-binding
534 (syntax-rules (quote)
535 ((_ type value) (cons type value))
537 ((_ type) (cons type '()))))
538 (define-syntax-rule (binding-type x)
540 (define-syntax-rule (binding-value x)
543 (define-syntax null-env (identifier-syntax '()))
546 (lambda (labels bindings r)
549 (extend-env (cdr labels) (cdr bindings)
550 (cons (cons (car labels) (car bindings)) r)))))
552 (define extend-var-env
553 ;; variant of extend-env that forms "lexical" binding
554 (lambda (labels vars r)
557 (extend-var-env (cdr labels) (cdr vars)
558 (cons (cons (car labels) (make-binding 'lexical (car vars))) r)))))
560 ;; we use a "macros only" environment in expansion of local macro
561 ;; definitions so that their definitions can use local macros without
562 ;; attempting to use other lexical identifiers.
563 (define macros-only-env
568 (if (memq (cadr a) '(macro syntax-parameter))
569 (cons a (macros-only-env (cdr r)))
570 (macros-only-env (cdr r)))))))
572 (define global-extend
573 (lambda (type sym val)
574 (put-global-definition-hook sym type val)))
577 ;; Conceptually, identifiers are always syntax objects. Internally,
578 ;; however, the wrap is sometimes maintained separately (a source of
579 ;; efficiency and confusion), so that symbols are also considered
580 ;; identifiers by id?. Externally, they are always wrapped.
582 (define nonsymbol-id?
584 (and (syntax-object? x)
585 (symbol? (syntax-object-expression x)))))
591 ((syntax-object? x) (symbol? (syntax-object-expression x)))
594 (define-syntax-rule (id-sym-name e)
596 (if (syntax-object? x)
597 (syntax-object-expression x)
600 (define id-sym-name&marks
602 (if (syntax-object? x)
604 (syntax-object-expression x)
605 (join-marks (wrap-marks w) (wrap-marks (syntax-object-wrap x))))
606 (values x (wrap-marks w)))))
608 ;; syntax object wraps
610 ;; <wrap> ::= ((<mark> ...) . (<subst> ...))
611 ;; <subst> ::= shift | <subs>
612 ;; <subs> ::= #(ribcage #(<sym> ...) #(<mark> ...) #(<label> ...))
613 ;; | #(ribcage (<sym> ...) (<mark> ...) (<label> ...))
615 (define-syntax make-wrap (identifier-syntax cons))
616 (define-syntax wrap-marks (identifier-syntax car))
617 (define-syntax wrap-subst (identifier-syntax cdr))
619 ;; labels must be comparable with "eq?", have read-write invariance,
620 ;; and distinct from symbols.
622 (string-append "l-" (session-id) (symbol->string (gensym "-"))))
628 (cons (gen-label) (gen-labels (cdr ls))))))
630 (define-structure (ribcage symnames marks labels))
632 (define-syntax empty-wrap (identifier-syntax '(())))
634 (define-syntax top-wrap (identifier-syntax '((top))))
636 (define-syntax-rule (top-marked? w)
637 (memq 'top (wrap-marks w)))
639 ;; Marks must be comparable with "eq?" and distinct from pairs and
640 ;; the symbol top. We do not use integers so that marks will remain
641 ;; unique even across file compiles.
643 (define-syntax the-anti-mark (identifier-syntax #f))
647 (make-wrap (cons the-anti-mark (wrap-marks w))
648 (cons 'shift (wrap-subst w)))))
650 (define-syntax-rule (new-mark)
651 (gensym (string-append "m-" (session-id) "-")))
653 ;; make-empty-ribcage and extend-ribcage maintain list-based ribcages for
654 ;; internal definitions, in which the ribcages are built incrementally
655 (define-syntax-rule (make-empty-ribcage)
656 (make-ribcage '() '() '()))
658 (define extend-ribcage!
659 ;; must receive ids with complete wraps
660 (lambda (ribcage id label)
661 (set-ribcage-symnames! ribcage
662 (cons (syntax-object-expression id)
663 (ribcage-symnames ribcage)))
664 (set-ribcage-marks! ribcage
665 (cons (wrap-marks (syntax-object-wrap id))
666 (ribcage-marks ribcage)))
667 (set-ribcage-labels! ribcage
668 (cons label (ribcage-labels ribcage)))))
670 ;; make-binding-wrap creates vector-based ribcages
671 (define make-binding-wrap
672 (lambda (ids labels w)
678 (let ((labelvec (list->vector labels)))
679 (let ((n (vector-length labelvec)))
680 (let ((symnamevec (make-vector n)) (marksvec (make-vector n)))
681 (let f ((ids ids) (i 0))
682 (if (not (null? ids))
684 (lambda () (id-sym-name&marks (car ids) w))
685 (lambda (symname marks)
686 (vector-set! symnamevec i symname)
687 (vector-set! marksvec i marks)
688 (f (cdr ids) (fx+ i 1))))))
689 (make-ribcage symnamevec marksvec labelvec))))
700 (let ((m1 (wrap-marks w1)) (s1 (wrap-subst w1)))
706 (smart-append s1 (wrap-subst w2))))
708 (smart-append m1 (wrap-marks w2))
709 (smart-append s1 (wrap-subst w2)))))))
713 (smart-append m1 m2)))
720 (eq? (car x) (car y))
721 (same-marks? (cdr x) (cdr y))))))
724 ;; Syntax objects use wraps to associate names with marked
725 ;; identifiers. This function returns the name corresponding to
726 ;; the given identifier and wrap, or the original identifier if no
727 ;; corresponding name was found.
729 ;; The name may be a string created by gen-label, indicating a
730 ;; lexical binding, or another syntax object, indicating a
731 ;; reference to a top-level definition created during a previous
734 ;; For lexical variables, finding a label simply amounts to
735 ;; looking for an entry with the same symbolic name and the same
736 ;; marks. Finding a toplevel definition is the same, except we
737 ;; also have to compare modules, hence the `mod' parameter.
738 ;; Instead of adding a separate entry in the ribcage for modules,
739 ;; which wouldn't be used for lexicals, we arrange for the entry
740 ;; for the name entry to be a pair with the module in its car, and
741 ;; the name itself in the cdr. So if the name that we find is a
742 ;; pair, we have to check modules.
744 ;; The identifer may be passed in wrapped or unwrapped. In any
745 ;; case, this routine returns either a symbol, a syntax object, or
749 (define-syntax-rule (first e)
750 ;; Rely on Guile's multiple-values truncation.
753 (lambda (sym subst marks mod)
756 (let ((fst (car subst)))
758 (search sym (cdr subst) (cdr marks) mod)
759 (let ((symnames (ribcage-symnames fst)))
760 (if (vector? symnames)
761 (search-vector-rib sym subst marks symnames fst mod)
762 (search-list-rib sym subst marks symnames fst mod))))))))
763 (define search-list-rib
764 (lambda (sym subst marks symnames ribcage mod)
765 (let f ((symnames symnames) (i 0))
767 ((null? symnames) (search sym (cdr subst) marks mod))
768 ((and (eq? (car symnames) sym)
769 (same-marks? marks (list-ref (ribcage-marks ribcage) i)))
770 (let ((n (list-ref (ribcage-labels ribcage) i)))
772 (if (equal? mod (car n))
773 (values (cdr n) marks)
774 (f (cdr symnames) (fx+ i 1)))
776 (else (f (cdr symnames) (fx+ i 1)))))))
777 (define search-vector-rib
778 (lambda (sym subst marks symnames ribcage mod)
779 (let ((n (vector-length symnames)))
782 ((fx= i n) (search sym (cdr subst) marks mod))
783 ((and (eq? (vector-ref symnames i) sym)
784 (same-marks? marks (vector-ref (ribcage-marks ribcage) i)))
785 (let ((n (vector-ref (ribcage-labels ribcage) i)))
787 (if (equal? mod (car n))
788 (values (cdr n) marks)
791 (else (f (fx+ i 1))))))))
794 (or (first (search id (wrap-subst w) (wrap-marks w) mod)) id))
796 (let ((id (syntax-object-expression id))
797 (w1 (syntax-object-wrap id))
798 (mod (syntax-object-module id)))
799 (let ((marks (join-marks (wrap-marks w) (wrap-marks w1))))
800 (call-with-values (lambda () (search id (wrap-subst w) marks mod))
801 (lambda (new-id marks)
803 (first (search id (wrap-subst w1) marks mod))
805 (else (syntax-violation 'id-var-name "invalid id" id)))))
807 ;; A helper procedure for syntax-locally-bound-identifiers, which
808 ;; itself is a helper for transformer procedures.
809 ;; `locally-bound-identifiers' returns a list of all bindings
810 ;; visible to a syntax object with the given wrap. They are in
811 ;; order from outer to inner.
813 ;; The purpose of this procedure is to give a transformer procedure
814 ;; references on bound identifiers, that the transformer can then
815 ;; introduce some of them in its output. As such, the identifiers
816 ;; are anti-marked, so that rebuild-macro-output doesn't apply new
819 (define locally-bound-identifiers
822 (lambda (subst results)
825 (let ((fst (car subst)))
827 (scan (cdr subst) results)
828 (let ((symnames (ribcage-symnames fst))
829 (marks (ribcage-marks fst)))
830 (if (vector? symnames)
831 (scan-vector-rib subst symnames marks results)
832 (scan-list-rib subst symnames marks results))))))))
833 (define scan-list-rib
834 (lambda (subst symnames marks results)
835 (let f ((symnames symnames) (marks marks) (results results))
837 (scan (cdr subst) results)
838 (f (cdr symnames) (cdr marks)
839 (cons (wrap (car symnames)
840 (anti-mark (make-wrap (car marks) subst))
843 (define scan-vector-rib
844 (lambda (subst symnames marks results)
845 (let ((n (vector-length symnames)))
846 (let f ((i 0) (results results))
848 (scan (cdr subst) results)
850 (cons (wrap (vector-ref symnames i)
851 (anti-mark (make-wrap (vector-ref marks i) subst))
854 (scan (wrap-subst w) '())))
856 ;; Returns three values: binding type, binding value, the module (for
857 ;; resolving toplevel vars).
858 (define (resolve-identifier id w r mod resolve-syntax-parameters?)
859 (define (resolve-syntax-parameters b)
860 (if (and resolve-syntax-parameters?
861 (eq? (binding-type b) 'syntax-parameter))
862 (or (assq-ref r (binding-value b))
863 (make-binding 'macro (car (binding-value b))))
865 (define (resolve-global var mod)
866 (let ((b (resolve-syntax-parameters
867 (or (get-global-definition-hook var mod)
868 (make-binding 'global)))))
869 (if (eq? (binding-type b) 'global)
870 (values 'global var mod)
871 (values (binding-type b) (binding-value b) mod))))
872 (define (resolve-lexical label mod)
873 (let ((b (resolve-syntax-parameters
874 (or (assq-ref r label)
875 (make-binding 'displaced-lexical)))))
876 (values (binding-type b) (binding-value b) mod)))
877 (let ((n (id-var-name id w mod)))
880 ;; Recursing allows syntax-parameterize to override
881 ;; macro-introduced syntax parameters.
882 (resolve-identifier n w r mod resolve-syntax-parameters?))
884 (resolve-global n (if (syntax-object? id)
885 (syntax-object-module id)
888 (resolve-lexical n (if (syntax-object? id)
889 (syntax-object-module id)
892 (error "unexpected id-var-name" id w n)))))
894 (define transformer-environment
897 (error "called outside the dynamic extent of a syntax transformer"))))
899 (define (with-transformer-environment k)
900 ((fluid-ref transformer-environment) k))
902 ;; free-id=? must be passed fully wrapped ids since (free-id=? x y)
903 ;; may be true even if (free-id=? (wrap x w) (wrap y w)) is not.
907 (let* ((mi (and (syntax-object? i) (syntax-object-module i)))
908 (mj (and (syntax-object? j) (syntax-object-module j)))
909 (ni (id-var-name i empty-wrap mi))
910 (nj (id-var-name j empty-wrap mj)))
911 (define (id-module-binding id mod)
915 (resolve-module (cdr mod))
916 ;; Either modules have not been booted, or we have a
917 ;; raw symbol coming in, which is possible.
921 ((syntax-object? ni) (free-id=? ni j))
922 ((syntax-object? nj) (free-id=? i nj))
924 ;; `i' is not lexically bound. Assert that `j' is free,
925 ;; and if so, compare their bindings, that they are either
926 ;; bound to the same variable, or both unbound and have
928 (and (eq? nj (id-sym-name j))
929 (let ((bi (id-module-binding i mi)))
931 (eq? bi (id-module-binding j mj))
932 (and (not (id-module-binding j mj))
934 (eq? (id-module-binding i mi) (id-module-binding j mj))))
936 ;; Otherwise `i' is bound, so check that `j' is bound, and
937 ;; bound to the same thing.
940 ;; bound-id=? may be passed unwrapped (or partially wrapped) ids as
941 ;; long as the missing portion of the wrap is common to both of the ids
942 ;; since (bound-id=? x y) iff (bound-id=? (wrap x w) (wrap y w))
946 (if (and (syntax-object? i) (syntax-object? j))
947 (and (eq? (syntax-object-expression i)
948 (syntax-object-expression j))
949 (same-marks? (wrap-marks (syntax-object-wrap i))
950 (wrap-marks (syntax-object-wrap j))))
953 ;; "valid-bound-ids?" returns #t if it receives a list of distinct ids.
954 ;; valid-bound-ids? may be passed unwrapped (or partially wrapped) ids
955 ;; as long as the missing portion of the wrap is common to all of the
958 (define valid-bound-ids?
960 (and (let all-ids? ((ids ids))
963 (all-ids? (cdr ids)))))
964 (distinct-bound-ids? ids))))
966 ;; distinct-bound-ids? expects a list of ids and returns #t if there are
967 ;; no duplicates. It is quadratic on the length of the id list; long
968 ;; lists could be sorted to make it more efficient. distinct-bound-ids?
969 ;; may be passed unwrapped (or partially wrapped) ids as long as the
970 ;; missing portion of the wrap is common to all of the ids.
972 (define distinct-bound-ids?
974 (let distinct? ((ids ids))
976 (and (not (bound-id-member? (car ids) (cdr ids)))
977 (distinct? (cdr ids)))))))
979 (define bound-id-member?
981 (and (not (null? list))
982 (or (bound-id=? x (car list))
983 (bound-id-member? x (cdr list))))))
985 ;; wrapping expressions and identifiers
990 ((and (null? (wrap-marks w)) (null? (wrap-subst w))) x)
993 (syntax-object-expression x)
994 (join-wraps w (syntax-object-wrap x))
995 (syntax-object-module x)))
997 (else (make-syntax-object x w defmod)))))
1000 (lambda (x w s defmod)
1001 (wrap (decorate-source x s) w defmod)))
1005 (define expand-sequence
1006 (lambda (body r w s mod)
1008 (let dobody ((body body) (r r) (w w) (mod mod))
1011 (let ((first (expand (car body) r w mod)))
1012 (cons first (dobody (cdr body) r w mod))))))))
1014 ;; At top-level, we allow mixed definitions and expressions. Like
1015 ;; expand-body we expand in two passes.
1017 ;; First, from left to right, we expand just enough to know what
1018 ;; expressions are definitions, syntax definitions, and splicing
1019 ;; statements (`begin'). If we anything needs evaluating at
1020 ;; expansion-time, it is expanded directly.
1022 ;; Otherwise we collect expressions to expand, in thunks, and then
1023 ;; expand them all at the end. This allows all syntax expanders
1024 ;; visible in a toplevel sequence to be visible during the
1025 ;; expansions of all normal definitions and expressions in the
1028 (define expand-top-sequence
1029 (lambda (body r w s m esew mod)
1030 (let* ((r (cons '("placeholder" . (placeholder)) r))
1031 (ribcage (make-empty-ribcage))
1032 (w (make-wrap (wrap-marks w) (cons ribcage (wrap-subst w)))))
1033 (define (record-definition! id var)
1034 (let ((mod (cons 'hygiene (module-name (current-module)))))
1035 ;; Ribcages map symbol+marks to names, mostly for
1036 ;; resolving lexicals. Here to add a mapping for toplevel
1037 ;; definitions we also need to match the module. So, we
1038 ;; put it in the name instead, and make id-var-name handle
1039 ;; the special case of names that are pairs. See the
1040 ;; comments in id-var-name for more.
1041 (extend-ribcage! ribcage id
1042 (cons (syntax-object-module id)
1043 (wrap var top-wrap mod)))))
1044 (define (macro-introduced-identifier? id)
1045 (not (equal? (wrap-marks (syntax-object-wrap id)) '(top))))
1046 (define (fresh-derived-name id orig-form)
1048 (syntax-object-expression id)
1051 ;; FIXME: `hash' currently stops descending into nested
1052 ;; data at some point, so it's less unique than we would
1053 ;; like. Also this encodes hash values into the ABI of
1054 ;; compiled modules; a problem?
1056 (hash (syntax->datum orig-form) most-positive-fixnum)
1058 (define (parse body r w s m esew mod)
1059 (let lp ((body body) (exps '()))
1063 (append (parse1 (car body) r w s m esew mod)
1065 (define (parse1 x r w s m esew mod)
1068 (syntax-type x r w (source-annotation x) ribcage mod #f))
1069 (lambda (type value form e w s mod)
1072 (let* ((id (wrap value w mod))
1074 (var (if (macro-introduced-identifier? id)
1075 (fresh-derived-name id x)
1076 (syntax-object-expression id))))
1077 (record-definition! id var)
1080 (let ((x (build-global-definition s var (expand e r w mod))))
1081 (top-level-eval-hook x mod)
1084 (build-global-definition s var (expand e r w mod)))))))
1085 ((define-syntax-form define-syntax-parameter-form)
1086 (let* ((id (wrap value w mod))
1088 (var (if (macro-introduced-identifier? id)
1089 (fresh-derived-name id x)
1090 (syntax-object-expression id))))
1091 (record-definition! id var)
1095 ((memq 'compile esew)
1096 (let ((e (expand-install-global var type (expand e r w mod))))
1097 (top-level-eval-hook e mod)
1098 (if (memq 'load esew)
1099 (list (lambda () e))
1103 (expand-install-global var type (expand e r w mod)))))
1106 (let ((e (expand-install-global var type (expand e r w mod))))
1107 (top-level-eval-hook e mod)
1108 (list (lambda () e))))
1110 (if (memq 'eval esew)
1111 (top-level-eval-hook
1112 (expand-install-global var type (expand e r w mod))
1118 (parse #'(e1 ...) r w s m esew mod))))
1119 ((local-syntax-form)
1120 (expand-local-syntax value e r w s mod
1121 (lambda (forms r w s mod)
1122 (parse forms r w s m esew mod))))
1125 ((_ (x ...) e1 e2 ...)
1126 (let ((when-list (parse-when-list e #'(x ...)))
1127 (body #'(e1 e2 ...)))
1128 (define (recurse m esew)
1129 (parse body r w s m esew mod))
1132 (if (memq 'eval when-list)
1133 (recurse (if (memq 'expand when-list) 'c&e 'e)
1136 (if (memq 'expand when-list)
1137 (top-level-eval-hook
1138 (expand-top-sequence body r w s 'e '(eval) mod)
1141 ((memq 'load when-list)
1142 (if (or (memq 'compile when-list)
1143 (memq 'expand when-list)
1144 (and (eq? m 'c&e) (memq 'eval when-list)))
1145 (recurse 'c&e '(compile load))
1146 (if (memq m '(c c&e))
1147 (recurse 'c '(load))
1149 ((or (memq 'compile when-list)
1150 (memq 'expand when-list)
1151 (and (eq? m 'c&e) (memq 'eval when-list)))
1152 (top-level-eval-hook
1153 (expand-top-sequence body r w s 'e '(eval) mod)
1161 (let ((x (expand-expr type value form e r w s mod)))
1162 (top-level-eval-hook x mod)
1165 (expand-expr type value form e r w s mod)))))))))
1166 (let ((exps (map (lambda (x) (x))
1167 (reverse (parse body r w s m esew mod)))))
1170 (build-sequence s exps))))))
1172 (define expand-install-global
1173 (lambda (name type e)
1174 (build-global-definition
1179 'make-syntax-transformer
1180 (if (eq? type 'define-syntax-parameter-form)
1181 (list (build-data no-source name)
1182 (build-data no-source 'syntax-parameter)
1183 (build-primcall no-source 'list (list e)))
1184 (list (build-data no-source name)
1185 (build-data no-source 'macro)
1188 (define parse-when-list
1189 (lambda (e when-list)
1190 ;; `when-list' is syntax'd version of list of situations. We
1191 ;; could match these keywords lexically, via free-id=?, but then
1192 ;; we twingle the definition of eval-when to the bindings of
1193 ;; eval, load, expand, and compile, which is totally unintended.
1194 ;; So do a symbolic match instead.
1195 (let ((result (strip when-list empty-wrap)))
1196 (let lp ((l result))
1199 (if (memq (car l) '(compile load eval expand))
1201 (syntax-violation 'eval-when "invalid situation" e
1204 ;; syntax-type returns seven values: type, value, form, e, w, s, and
1205 ;; mod. The first two are described in the table below.
1207 ;; type value explanation
1208 ;; -------------------------------------------------------------------
1209 ;; core procedure core singleton
1210 ;; core-form procedure core form
1211 ;; module-ref procedure @ or @@ singleton
1212 ;; lexical name lexical variable reference
1213 ;; global name global variable reference
1214 ;; begin none begin keyword
1215 ;; define none define keyword
1216 ;; define-syntax none define-syntax keyword
1217 ;; define-syntax-parameter none define-syntax-parameter keyword
1218 ;; local-syntax rec? letrec-syntax/let-syntax keyword
1219 ;; eval-when none eval-when keyword
1220 ;; syntax level pattern variable
1221 ;; displaced-lexical none displaced lexical identifier
1222 ;; lexical-call name call to lexical variable
1223 ;; global-call name call to global variable
1224 ;; primitive-call name call to primitive
1225 ;; call none any other call
1226 ;; begin-form none begin expression
1227 ;; define-form id variable definition
1228 ;; define-syntax-form id syntax definition
1229 ;; define-syntax-parameter-form id syntax parameter definition
1230 ;; local-syntax-form rec? syntax definition
1231 ;; eval-when-form none eval-when form
1232 ;; constant none self-evaluating datum
1233 ;; other none anything else
1235 ;; form is the entire form. For definition forms (define-form,
1236 ;; define-syntax-form, and define-syntax-parameter-form), e is the
1237 ;; rhs expression. For all others, e is the entire form. w is the
1238 ;; wrap for both form and e. s is the source for the entire form.
1239 ;; mod is the module for both form and e.
1241 ;; syntax-type expands macros and unwraps as necessary to get to one
1242 ;; of the forms above. It also parses definition forms, although
1243 ;; perhaps this should be done by the consumer.
1246 (lambda (e r w s rib mod for-car?)
1249 (call-with-values (lambda () (resolve-identifier e w r mod #t))
1250 (lambda (type value mod*)
1254 (values type value e e w s mod)
1255 (syntax-type (expand-macro value e r w s rib mod)
1256 r empty-wrap s rib mod #f)))
1258 ;; Toplevel definitions may resolve to bindings with
1259 ;; different names or in different modules.
1260 (values type value e value w s mod*))
1261 (else (values type value e e w s mod))))))
1263 (let ((first (car e)))
1265 (lambda () (syntax-type first r w s rib mod #t))
1266 (lambda (ftype fval fform fe fw fs fmod)
1269 (values 'lexical-call fval e e w s mod))
1271 (if (equal? fmod '(primitive))
1272 (values 'primitive-call fval e e w s mod)
1273 ;; If we got here via an (@@ ...) expansion, we
1274 ;; need to make sure the fmod information is
1275 ;; propagated back correctly -- hence this
1277 (values 'global-call (make-syntax-object fval w fmod)
1280 (syntax-type (expand-macro fval e r w s rib mod)
1281 r empty-wrap s rib mod for-car?))
1283 (call-with-values (lambda () (fval e r w mod))
1284 (lambda (e r w s mod)
1285 (syntax-type e r w s rib mod for-car?))))
1287 (values 'core-form fval e e w s mod))
1289 (values 'local-syntax-form fval e e w s mod))
1291 (values 'begin-form #f e e w s mod))
1293 (values 'eval-when-form #f e e w s mod))
1298 (values 'define-form #'name e #'val w s mod))
1299 ((_ (name . args) e1 e2 ...)
1301 (valid-bound-ids? (lambda-var-list #'args)))
1302 ;; need lambda here...
1303 (values 'define-form (wrap #'name w mod)
1306 (cons #'lambda (wrap #'(args e1 e2 ...) w mod))
1311 (values 'define-form (wrap #'name w mod)
1314 empty-wrap s mod))))
1319 (values 'define-syntax-form #'name e #'val w s mod))))
1320 ((define-syntax-parameter)
1324 (values 'define-syntax-parameter-form #'name e #'val w s mod))))
1326 (values 'call #f e e w s mod)))))))
1328 (syntax-type (syntax-object-expression e)
1330 (join-wraps w (syntax-object-wrap e))
1331 (or (source-annotation e) s) rib
1332 (or (syntax-object-module e) mod) for-car?))
1333 ((self-evaluating? e) (values 'constant #f e e w s mod))
1334 (else (values 'other #f e e w s mod)))))
1339 (lambda () (syntax-type e r w (source-annotation e) #f mod #f))
1340 (lambda (type value form e w s mod)
1341 (expand-expr type value form e r w s mod)))))
1344 (lambda (type value form e r w s mod)
1347 (build-lexical-reference 'value s e value))
1349 ;; apply transformer
1350 (value e r w s mod))
1352 (call-with-values (lambda () (value e r w mod))
1353 (lambda (e r w s mod)
1354 (expand e r w mod))))
1358 (build-lexical-reference 'fun (source-annotation id)
1359 (if (syntax-object? id)
1366 (build-global-reference (source-annotation (car e))
1367 (if (syntax-object? value)
1368 (syntax-object-expression value)
1370 (if (syntax-object? value)
1371 (syntax-object-module value)
1379 (map (lambda (e) (expand e r w mod))
1381 ((constant) (build-data s (strip (source-wrap e w s mod) empty-wrap)))
1382 ((global) (build-global-reference s value mod))
1383 ((call) (expand-call (expand (car e) r w mod) e r w s mod))
1386 ((_ e1 e2 ...) (expand-sequence #'(e1 e2 ...) r w s mod))
1388 (syntax-violation #f "sequence of zero expressions"
1389 (source-wrap e w s mod)))))
1390 ((local-syntax-form)
1391 (expand-local-syntax value e r w s mod expand-sequence))
1394 ((_ (x ...) e1 e2 ...)
1395 (let ((when-list (parse-when-list e #'(x ...))))
1396 (if (memq 'eval when-list)
1397 (expand-sequence #'(e1 e2 ...) r w s mod)
1399 ((define-form define-syntax-form define-syntax-parameter-form)
1400 (syntax-violation #f "definition in expression context, where definitions are not allowed,"
1401 (source-wrap form w s mod)))
1403 (syntax-violation #f "reference to pattern variable outside syntax form"
1404 (source-wrap e w s mod)))
1405 ((displaced-lexical)
1406 (syntax-violation #f "reference to identifier outside its scope"
1407 (source-wrap e w s mod)))
1408 (else (syntax-violation #f "unexpected syntax"
1409 (source-wrap e w s mod))))))
1412 (lambda (x e r w s mod)
1416 (map (lambda (e) (expand e r w mod)) #'(e1 ...)))))))
1418 ;; (What follows is my interpretation of what's going on here -- Andy)
1420 ;; A macro takes an expression, a tree, the leaves of which are identifiers
1421 ;; and datums. Identifiers are symbols along with a wrap and a module. For
1422 ;; efficiency, subtrees that share wraps and modules may be grouped as one
1425 ;; Going into the expansion, the expression is given an anti-mark, which
1426 ;; logically propagates to all leaves. Then, in the new expression returned
1427 ;; from the transfomer, if we see an expression with an anti-mark, we know it
1428 ;; pertains to the original expression; conversely, expressions without the
1429 ;; anti-mark are known to be introduced by the transformer.
1431 ;; OK, good until now. We know this algorithm does lexical scoping
1432 ;; appropriately because it's widely known in the literature, and psyntax is
1433 ;; widely used. But what about modules? Here we're on our own. What we do is
1434 ;; to mark the module of expressions produced by a macro as pertaining to the
1435 ;; module that was current when the macro was defined -- that is, free
1436 ;; identifiers introduced by a macro are scoped in the macro's module, not in
1437 ;; the expansion's module. Seems to work well.
1439 ;; The only wrinkle is when we want a macro to expand to code in another
1440 ;; module, as is the case for the r6rs `library' form -- the body expressions
1441 ;; should be scoped relative the the new module, the one defined by the macro.
1442 ;; For that, use `(@@ mod-name body)'.
1444 ;; Part of the macro output will be from the site of the macro use and part
1445 ;; from the macro definition. We allow source information from the macro use
1446 ;; to pass through, but we annotate the parts coming from the macro with the
1447 ;; source location information corresponding to the macro use. It would be
1448 ;; really nice if we could also annotate introduced expressions with the
1449 ;; locations corresponding to the macro definition, but that is not yet
1451 (define expand-macro
1452 (lambda (p e r w s rib mod)
1453 (define rebuild-macro-output
1457 (cons (rebuild-macro-output (car x) m)
1458 (rebuild-macro-output (cdr x) m))
1461 (let ((w (syntax-object-wrap x)))
1462 (let ((ms (wrap-marks w)) (ss (wrap-subst w)))
1463 (if (and (pair? ms) (eq? (car ms) the-anti-mark))
1464 ;; output is from original text
1466 (syntax-object-expression x)
1467 (make-wrap (cdr ms) (if rib (cons rib (cdr ss)) (cdr ss)))
1468 (syntax-object-module x))
1469 ;; output introduced by macro
1471 (decorate-source (syntax-object-expression x) s)
1472 (make-wrap (cons m ms)
1474 (cons rib (cons 'shift ss))
1476 (syntax-object-module x))))))
1479 (let* ((n (vector-length x))
1480 (v (decorate-source (make-vector n) s)))
1481 (do ((i 0 (fx+ i 1)))
1484 (rebuild-macro-output (vector-ref x i) m)))))
1486 (syntax-violation #f "encountered raw symbol in macro output"
1487 (source-wrap e w (wrap-subst w) mod) x))
1488 (else (decorate-source x s)))))
1489 (with-fluids ((transformer-environment
1490 (lambda (k) (k e r w s rib mod))))
1491 (rebuild-macro-output (p (source-wrap e (anti-mark w) s mod))
1495 ;; In processing the forms of the body, we create a new, empty wrap.
1496 ;; This wrap is augmented (destructively) each time we discover that
1497 ;; the next form is a definition. This is done:
1499 ;; (1) to allow the first nondefinition form to be a call to
1500 ;; one of the defined ids even if the id previously denoted a
1501 ;; definition keyword or keyword for a macro expanding into a
1503 ;; (2) to prevent subsequent definition forms (but unfortunately
1504 ;; not earlier ones) and the first nondefinition form from
1505 ;; confusing one of the bound identifiers for an auxiliary
1507 ;; (3) so that we do not need to restart the expansion of the
1508 ;; first nondefinition form, which is problematic anyway
1509 ;; since it might be the first element of a begin that we
1510 ;; have just spliced into the body (meaning if we restarted,
1511 ;; we'd really need to restart with the begin or the macro
1512 ;; call that expanded into the begin, and we'd have to give
1513 ;; up allowing (begin <defn>+ <expr>+), which is itself
1514 ;; problematic since we don't know if a begin contains only
1515 ;; definitions until we've expanded it).
1517 ;; Before processing the body, we also create a new environment
1518 ;; containing a placeholder for the bindings we will add later and
1519 ;; associate this environment with each form. In processing a
1520 ;; let-syntax or letrec-syntax, the associated environment may be
1521 ;; augmented with local keyword bindings, so the environment may
1522 ;; be different for different forms in the body. Once we have
1523 ;; gathered up all of the definitions, we evaluate the transformer
1524 ;; expressions and splice into r at the placeholder the new variable
1525 ;; and keyword bindings. This allows let-syntax or letrec-syntax
1526 ;; forms local to a portion or all of the body to shadow the
1527 ;; definition bindings.
1529 ;; Subforms of a begin, let-syntax, or letrec-syntax are spliced
1532 ;; outer-form is fully wrapped w/source
1533 (lambda (body outer-form r w mod)
1534 (let* ((r (cons '("placeholder" . (placeholder)) r))
1535 (ribcage (make-empty-ribcage))
1536 (w (make-wrap (wrap-marks w) (cons ribcage (wrap-subst w)))))
1537 (let parse ((body (map (lambda (x) (cons r (wrap x w mod))) body))
1538 (ids '()) (labels '())
1539 (var-ids '()) (vars '()) (vals '()) (bindings '()))
1541 (syntax-violation #f "no expressions in body" outer-form)
1542 (let ((e (cdar body)) (er (caar body)))
1544 (lambda () (syntax-type e er empty-wrap (source-annotation e) ribcage mod #f))
1545 (lambda (type value form e w s mod)
1548 (let ((id (wrap value w mod)) (label (gen-label)))
1549 (let ((var (gen-var id)))
1550 (extend-ribcage! ribcage id label)
1552 (cons id ids) (cons label labels)
1554 (cons var vars) (cons (cons er (wrap e w mod)) vals)
1555 (cons (make-binding 'lexical var) bindings)))))
1556 ((define-syntax-form)
1557 (let ((id (wrap value w mod))
1559 (trans-r (macros-only-env er)))
1560 (extend-ribcage! ribcage id label)
1561 ;; As required by R6RS, evaluate the right-hand-sides of internal
1562 ;; syntax definition forms and add their transformers to the
1563 ;; compile-time environment immediately, so that the newly-defined
1564 ;; keywords may be used in definition context within the same
1566 (set-cdr! r (extend-env
1570 (eval-local-transformer
1571 (expand e trans-r w mod)
1574 (parse (cdr body) (cons id ids) labels var-ids vars vals bindings)))
1575 ((define-syntax-parameter-form)
1576 ;; Same as define-syntax-form, but different format of the binding.
1577 (let ((id (wrap value w mod))
1579 (trans-r (macros-only-env er)))
1580 (extend-ribcage! ribcage id label)
1581 (set-cdr! r (extend-env
1585 (list (eval-local-transformer
1586 (expand e trans-r w mod)
1589 (parse (cdr body) (cons id ids) labels var-ids vars vals bindings)))
1593 (parse (let f ((forms #'(e1 ...)))
1596 (cons (cons er (wrap (car forms) w mod))
1598 ids labels var-ids vars vals bindings))))
1599 ((local-syntax-form)
1600 (expand-local-syntax value e er w s mod
1601 (lambda (forms er w s mod)
1602 (parse (let f ((forms forms))
1605 (cons (cons er (wrap (car forms) w mod))
1607 ids labels var-ids vars vals bindings))))
1608 (else ; found a non-definition
1610 (build-sequence no-source
1612 (expand (cdr x) (car x) empty-wrap mod))
1613 (cons (cons er (source-wrap e w s mod))
1616 (if (not (valid-bound-ids? ids))
1618 #f "invalid or duplicate identifier in definition"
1620 (set-cdr! r (extend-env labels bindings (cdr r)))
1621 (build-letrec no-source #t
1622 (reverse (map syntax->datum var-ids))
1625 (expand (cdr x) (car x) empty-wrap mod))
1627 (build-sequence no-source
1629 (expand (cdr x) (car x) empty-wrap mod))
1630 (cons (cons er (source-wrap e w s mod))
1631 (cdr body)))))))))))))))))
1633 (define expand-local-syntax
1634 (lambda (rec? e r w s mod k)
1636 ((_ ((id val) ...) e1 e2 ...)
1637 (let ((ids #'(id ...)))
1638 (if (not (valid-bound-ids? ids))
1639 (syntax-violation #f "duplicate bound keyword" e)
1640 (let ((labels (gen-labels ids)))
1641 (let ((new-w (make-binding-wrap ids labels w)))
1645 (let ((w (if rec? new-w w))
1646 (trans-r (macros-only-env r)))
1648 (make-binding 'macro
1649 (eval-local-transformer
1650 (expand x trans-r w mod)
1657 (_ (syntax-violation #f "bad local syntax definition"
1658 (source-wrap e w s mod))))))
1660 (define eval-local-transformer
1661 (lambda (expanded mod)
1662 (let ((p (local-eval-hook expanded mod)))
1665 (syntax-violation #f "nonprocedure transformer" p)))))
1669 (build-void no-source)))
1673 (and (nonsymbol-id? x)
1674 (free-id=? x #'(... ...)))))
1676 (define lambda-formals
1678 (define (req args rreq)
1679 (syntax-case args ()
1681 (check (reverse rreq) #f))
1683 (req #'b (cons #'a rreq)))
1685 (check (reverse rreq) #'r))
1687 (syntax-violation 'lambda "invalid argument list" orig-args args))))
1688 (define (check req rest)
1690 ((distinct-bound-ids? (if rest (cons rest req) req))
1691 (values req #f rest #f))
1693 (syntax-violation 'lambda "duplicate identifier in argument list"
1695 (req orig-args '())))
1697 (define expand-simple-lambda
1698 (lambda (e r w s mod req rest meta body)
1699 (let* ((ids (if rest (append req (list rest)) req))
1700 (vars (map gen-var ids))
1701 (labels (gen-labels ids)))
1702 (build-simple-lambda
1704 (map syntax->datum req) (and rest (syntax->datum rest)) vars
1706 (expand-body body (source-wrap e w s mod)
1707 (extend-var-env labels vars r)
1708 (make-binding-wrap ids labels w)
1711 (define lambda*-formals
1713 (define (req args rreq)
1714 (syntax-case args ()
1716 (check (reverse rreq) '() #f '()))
1718 (req #'b (cons #'a rreq)))
1719 ((a . b) (eq? (syntax->datum #'a) #:optional)
1720 (opt #'b (reverse rreq) '()))
1721 ((a . b) (eq? (syntax->datum #'a) #:key)
1722 (key #'b (reverse rreq) '() '()))
1723 ((a b) (eq? (syntax->datum #'a) #:rest)
1724 (rest #'b (reverse rreq) '() '()))
1726 (rest #'r (reverse rreq) '() '()))
1728 (syntax-violation 'lambda* "invalid argument list" orig-args args))))
1729 (define (opt args req ropt)
1730 (syntax-case args ()
1732 (check req (reverse ropt) #f '()))
1734 (opt #'b req (cons #'(a #f) ropt)))
1735 (((a init) . b) (id? #'a)
1736 (opt #'b req (cons #'(a init) ropt)))
1737 ((a . b) (eq? (syntax->datum #'a) #:key)
1738 (key #'b req (reverse ropt) '()))
1739 ((a b) (eq? (syntax->datum #'a) #:rest)
1740 (rest #'b req (reverse ropt) '()))
1742 (rest #'r req (reverse ropt) '()))
1744 (syntax-violation 'lambda* "invalid optional argument list"
1746 (define (key args req opt rkey)
1747 (syntax-case args ()
1749 (check req opt #f (cons #f (reverse rkey))))
1751 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1752 (key #'b req opt (cons #'(k a #f) rkey))))
1753 (((a init) . b) (id? #'a)
1754 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1755 (key #'b req opt (cons #'(k a init) rkey))))
1756 (((a init k) . b) (and (id? #'a)
1757 (keyword? (syntax->datum #'k)))
1758 (key #'b req opt (cons #'(k a init) rkey)))
1759 ((aok) (eq? (syntax->datum #'aok) #:allow-other-keys)
1760 (check req opt #f (cons #t (reverse rkey))))
1761 ((aok a b) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1762 (eq? (syntax->datum #'a) #:rest))
1763 (rest #'b req opt (cons #t (reverse rkey))))
1764 ((aok . r) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1766 (rest #'r req opt (cons #t (reverse rkey))))
1767 ((a b) (eq? (syntax->datum #'a) #:rest)
1768 (rest #'b req opt (cons #f (reverse rkey))))
1770 (rest #'r req opt (cons #f (reverse rkey))))
1772 (syntax-violation 'lambda* "invalid keyword argument list"
1774 (define (rest args req opt kw)
1775 (syntax-case args ()
1777 (check req opt #'r kw))
1779 (syntax-violation 'lambda* "invalid rest argument"
1781 (define (check req opt rest kw)
1783 ((distinct-bound-ids?
1784 (append req (map car opt) (if rest (list rest) '())
1785 (if (pair? kw) (map cadr (cdr kw)) '())))
1786 (values req opt rest kw))
1788 (syntax-violation 'lambda* "duplicate identifier in argument list"
1790 (req orig-args '())))
1792 (define expand-lambda-case
1793 (lambda (e r w s mod get-formals clauses)
1794 (define (parse-req req opt rest kw body)
1795 (let ((vars (map gen-var req))
1796 (labels (gen-labels req)))
1797 (let ((r* (extend-var-env labels vars r))
1798 (w* (make-binding-wrap req labels w)))
1799 (parse-opt (map syntax->datum req)
1800 opt rest kw body (reverse vars) r* w* '() '()))))
1801 (define (parse-opt req opt rest kw body vars r* w* out inits)
1804 (syntax-case (car opt) ()
1806 (let* ((v (gen-var #'id))
1807 (l (gen-labels (list v)))
1808 (r** (extend-var-env l (list v) r*))
1809 (w** (make-binding-wrap (list #'id) l w*)))
1810 (parse-opt req (cdr opt) rest kw body (cons v vars)
1811 r** w** (cons (syntax->datum #'id) out)
1812 (cons (expand #'i r* w* mod) inits))))))
1814 (let* ((v (gen-var rest))
1815 (l (gen-labels (list v)))
1816 (r* (extend-var-env l (list v) r*))
1817 (w* (make-binding-wrap (list rest) l w*)))
1818 (parse-kw req (if (pair? out) (reverse out) #f)
1819 (syntax->datum rest)
1820 (if (pair? kw) (cdr kw) kw)
1821 body (cons v vars) r* w*
1822 (if (pair? kw) (car kw) #f)
1825 (parse-kw req (if (pair? out) (reverse out) #f) #f
1826 (if (pair? kw) (cdr kw) kw)
1828 (if (pair? kw) (car kw) #f)
1830 (define (parse-kw req opt rest kw body vars r* w* aok out inits)
1833 (syntax-case (car kw) ()
1835 (let* ((v (gen-var #'id))
1836 (l (gen-labels (list v)))
1837 (r** (extend-var-env l (list v) r*))
1838 (w** (make-binding-wrap (list #'id) l w*)))
1839 (parse-kw req opt rest (cdr kw) body (cons v vars)
1841 (cons (list (syntax->datum #'k)
1842 (syntax->datum #'id)
1845 (cons (expand #'i r* w* mod) inits))))))
1847 (parse-body req opt rest
1848 (if (or aok (pair? out)) (cons aok (reverse out)) #f)
1849 body (reverse vars) r* w* (reverse inits) '()))))
1850 (define (parse-body req opt rest kw body vars r* w* inits meta)
1851 (syntax-case body ()
1852 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
1853 (parse-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1856 . ,(syntax->datum #'docstring))))))
1857 ((#((k . v) ...) e1 e2 ...)
1858 (parse-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1859 (append meta (syntax->datum #'((k . v) ...)))))
1861 (values meta req opt rest kw inits vars
1862 (expand-body #'(e1 e2 ...) (source-wrap e w s mod)
1865 (syntax-case clauses ()
1866 (() (values '() #f))
1867 (((args e1 e2 ...) (args* e1* e2* ...) ...)
1868 (call-with-values (lambda () (get-formals #'args))
1869 (lambda (req opt rest kw)
1870 (call-with-values (lambda ()
1871 (parse-req req opt rest kw #'(e1 e2 ...)))
1872 (lambda (meta req opt rest kw inits vars body)
1875 (expand-lambda-case e r w s mod get-formals
1876 #'((args* e1* e2* ...) ...)))
1877 (lambda (meta* else*)
1880 (build-lambda-case s req opt rest kw inits vars
1881 body else*))))))))))))
1885 ;; strips syntax-objects down to top-wrap
1887 ;; since only the head of a list is annotated by the reader, not each pair
1888 ;; in the spine, we also check for pairs whose cars are annotated in case
1889 ;; we've been passed the cdr of an annotated list
1898 (strip (syntax-object-expression x) (syntax-object-wrap x)))
1900 (let ((a (f (car x))) (d (f (cdr x))))
1901 (if (and (eq? a (car x)) (eq? d (cdr x)))
1905 (let ((old (vector->list x)))
1906 (let ((new (map f old)))
1907 ;; inlined and-map with two args
1908 (let lp ((l1 old) (l2 new))
1911 (if (eq? (car l1) (car l2))
1912 (lp (cdr l1) (cdr l2))
1913 (list->vector new)))))))
1916 ;; lexical variables
1920 (let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
1921 (build-lexical-var no-source id))))
1923 ;; appears to return a reversed list
1924 (define lambda-var-list
1926 (let lvl ((vars vars) (ls '()) (w empty-wrap))
1928 ((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
1929 ((id? vars) (cons (wrap vars w #f) ls))
1931 ((syntax-object? vars)
1932 (lvl (syntax-object-expression vars)
1934 (join-wraps w (syntax-object-wrap vars))))
1935 ;; include anything else to be caught by subsequent error
1937 (else (cons vars ls))))))
1939 ;; core transformers
1941 (global-extend 'local-syntax 'letrec-syntax #t)
1942 (global-extend 'local-syntax 'let-syntax #f)
1945 'core 'syntax-parameterize
1946 (lambda (e r w s mod)
1948 ((_ ((var val) ...) e1 e2 ...)
1949 (valid-bound-ids? #'(var ...))
1953 (lambda () (resolve-identifier x w r mod #f))
1954 (lambda (type value mod)
1956 ((displaced-lexical)
1957 (syntax-violation 'syntax-parameterize
1958 "identifier out of context"
1960 (source-wrap x w s mod)))
1964 (syntax-violation 'syntax-parameterize
1965 "invalid syntax parameter"
1967 (source-wrap x w s mod)))))))
1970 (let ((trans-r (macros-only-env r)))
1974 (eval-local-transformer (expand x trans-r w mod) mod)))
1976 (expand-body #'(e1 e2 ...)
1977 (source-wrap e w s mod)
1978 (extend-env names bindings r)
1981 (_ (syntax-violation 'syntax-parameterize "bad syntax"
1982 (source-wrap e w s mod))))))
1984 (global-extend 'core 'quote
1985 (lambda (e r w s mod)
1987 ((_ e) (build-data s (strip #'e w)))
1988 (_ (syntax-violation 'quote "bad syntax"
1989 (source-wrap e w s mod))))))
1995 (lambda (src e r maps ellipsis? mod)
1997 (call-with-values (lambda ()
1998 (resolve-identifier e empty-wrap r mod #f))
1999 (lambda (type value mod)
2003 (lambda () (gen-ref src (car value) (cdr value) maps))
2005 (values `(ref ,var) maps))))
2008 (syntax-violation 'syntax "misplaced ellipsis" src)
2009 (values `(quote ,e) maps))))))
2013 (gen-syntax src #'e r maps (lambda (x) #f) mod))
2015 ;; this could be about a dozen lines of code, except that we
2016 ;; choose to handle #'(x ... ...) forms
2022 (gen-syntax src #'x r
2023 (cons '() maps) ellipsis? mod))
2025 (if (null? (car maps))
2026 (syntax-violation 'syntax "extra ellipsis"
2028 (values (gen-map x (car maps))
2036 (lambda () (k (cons '() maps)))
2038 (if (null? (car maps))
2039 (syntax-violation 'syntax "extra ellipsis" src)
2040 (values (gen-mappend x (car maps))
2042 (_ (call-with-values
2043 (lambda () (gen-syntax src y r maps ellipsis? mod))
2046 (lambda () (k maps))
2048 (values (gen-append x y) maps)))))))))
2051 (lambda () (gen-syntax src #'x r maps ellipsis? mod))
2054 (lambda () (gen-syntax src #'y r maps ellipsis? mod))
2055 (lambda (y maps) (values (gen-cons x y) maps))))))
2059 (gen-syntax src #'(e1 e2 ...) r maps ellipsis? mod))
2060 (lambda (e maps) (values (gen-vector e) maps))))
2061 (_ (values `(quote ,e) maps))))))
2064 (lambda (src var level maps)
2068 (syntax-violation 'syntax "missing ellipsis" src)
2070 (lambda () (gen-ref src var (fx- level 1) (cdr maps)))
2071 (lambda (outer-var outer-maps)
2072 (let ((b (assq outer-var (car maps))))
2074 (values (cdr b) maps)
2075 (let ((inner-var (gen-var 'tmp)))
2077 (cons (cons (cons outer-var inner-var)
2079 outer-maps)))))))))))
2083 `(apply (primitive append) ,(gen-map e map-env))))
2087 (let ((formals (map cdr map-env))
2088 (actuals (map (lambda (x) `(ref ,(car x))) map-env)))
2091 ;; identity map equivalence:
2092 ;; (map (lambda (x) x) y) == y
2095 (lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
2097 ;; eta map equivalence:
2098 ;; (map (lambda (x ...) (f x ...)) y ...) == (map f y ...)
2099 `(map (primitive ,(car e))
2100 ,@(map (let ((r (map cons formals actuals)))
2101 (lambda (x) (cdr (assq (cadr x) r))))
2103 (else `(map (lambda ,formals ,e) ,@actuals))))))
2109 (if (eq? (car x) 'quote)
2110 `(quote (,(cadr x) . ,(cadr y)))
2111 (if (eq? (cadr y) '())
2114 ((list) `(list ,x ,@(cdr y)))
2115 (else `(cons ,x ,y)))))
2119 (if (equal? y '(quote ()))
2126 ((eq? (car x) 'list) `(vector ,@(cdr x)))
2127 ((eq? (car x) 'quote) `(quote #(,@(cadr x))))
2128 (else `(list->vector ,x)))))
2134 ((ref) (build-lexical-reference 'value no-source (cadr x) (cadr x)))
2135 ((primitive) (build-primref no-source (cadr x)))
2136 ((quote) (build-data no-source (cadr x)))
2138 (if (list? (cadr x))
2139 (build-simple-lambda no-source (cadr x) #f (cadr x) '() (regen (caddr x)))
2140 (error "how did we get here" x)))
2141 (else (build-primcall no-source (car x) (map regen (cdr x)))))))
2143 (lambda (e r w s mod)
2144 (let ((e (source-wrap e w s mod)))
2148 (lambda () (gen-syntax e #'x r '() ellipsis? mod))
2149 (lambda (e maps) (regen e))))
2150 (_ (syntax-violation 'syntax "bad `syntax' form" e)))))))
2152 (global-extend 'core 'lambda
2153 (lambda (e r w s mod)
2156 (call-with-values (lambda () (lambda-formals #'args))
2157 (lambda (req opt rest kw)
2158 (let lp ((body #'(e1 e2 ...)) (meta '()))
2159 (syntax-case body ()
2160 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
2164 . ,(syntax->datum #'docstring))))))
2165 ((#((k . v) ...) e1 e2 ...)
2167 (append meta (syntax->datum #'((k . v) ...)))))
2168 (_ (expand-simple-lambda e r w s mod req rest meta body)))))))
2169 (_ (syntax-violation 'lambda "bad lambda" e)))))
2171 (global-extend 'core 'lambda*
2172 (lambda (e r w s mod)
2177 (expand-lambda-case e r w s mod
2178 lambda*-formals #'((args e1 e2 ...))))
2179 (lambda (meta lcase)
2180 (build-case-lambda s meta lcase))))
2181 (_ (syntax-violation 'lambda "bad lambda*" e)))))
2183 (global-extend 'core 'case-lambda
2184 (lambda (e r w s mod)
2185 (define (build-it meta clauses)
2188 (expand-lambda-case e r w s mod
2191 (lambda (meta* lcase)
2192 (build-case-lambda s (append meta meta*) lcase))))
2194 ((_ (args e1 e2 ...) ...)
2195 (build-it '() #'((args e1 e2 ...) ...)))
2196 ((_ docstring (args e1 e2 ...) ...)
2197 (string? (syntax->datum #'docstring))
2198 (build-it `((documentation
2199 . ,(syntax->datum #'docstring)))
2200 #'((args e1 e2 ...) ...)))
2201 (_ (syntax-violation 'case-lambda "bad case-lambda" e)))))
2203 (global-extend 'core 'case-lambda*
2204 (lambda (e r w s mod)
2205 (define (build-it meta clauses)
2208 (expand-lambda-case e r w s mod
2211 (lambda (meta* lcase)
2212 (build-case-lambda s (append meta meta*) lcase))))
2214 ((_ (args e1 e2 ...) ...)
2215 (build-it '() #'((args e1 e2 ...) ...)))
2216 ((_ docstring (args e1 e2 ...) ...)
2217 (string? (syntax->datum #'docstring))
2218 (build-it `((documentation
2219 . ,(syntax->datum #'docstring)))
2220 #'((args e1 e2 ...) ...)))
2221 (_ (syntax-violation 'case-lambda "bad case-lambda*" e)))))
2223 (global-extend 'core 'let
2225 (define (expand-let e r w s mod constructor ids vals exps)
2226 (if (not (valid-bound-ids? ids))
2227 (syntax-violation 'let "duplicate bound variable" e)
2228 (let ((labels (gen-labels ids))
2229 (new-vars (map gen-var ids)))
2230 (let ((nw (make-binding-wrap ids labels w))
2231 (nr (extend-var-env labels new-vars r)))
2233 (map syntax->datum ids)
2235 (map (lambda (x) (expand x r w mod)) vals)
2236 (expand-body exps (source-wrap e nw s mod)
2238 (lambda (e r w s mod)
2240 ((_ ((id val) ...) e1 e2 ...)
2241 (and-map id? #'(id ...))
2242 (expand-let e r w s mod
2247 ((_ f ((id val) ...) e1 e2 ...)
2248 (and (id? #'f) (and-map id? #'(id ...)))
2249 (expand-let e r w s mod
2254 (_ (syntax-violation 'let "bad let" (source-wrap e w s mod)))))))
2257 (global-extend 'core 'letrec
2258 (lambda (e r w s mod)
2260 ((_ ((id val) ...) e1 e2 ...)
2261 (and-map id? #'(id ...))
2262 (let ((ids #'(id ...)))
2263 (if (not (valid-bound-ids? ids))
2264 (syntax-violation 'letrec "duplicate bound variable" e)
2265 (let ((labels (gen-labels ids))
2266 (new-vars (map gen-var ids)))
2267 (let ((w (make-binding-wrap ids labels w))
2268 (r (extend-var-env labels new-vars r)))
2270 (map syntax->datum ids)
2272 (map (lambda (x) (expand x r w mod)) #'(val ...))
2273 (expand-body #'(e1 e2 ...)
2274 (source-wrap e w s mod) r w mod)))))))
2275 (_ (syntax-violation 'letrec "bad letrec" (source-wrap e w s mod))))))
2278 (global-extend 'core 'letrec*
2279 (lambda (e r w s mod)
2281 ((_ ((id val) ...) e1 e2 ...)
2282 (and-map id? #'(id ...))
2283 (let ((ids #'(id ...)))
2284 (if (not (valid-bound-ids? ids))
2285 (syntax-violation 'letrec* "duplicate bound variable" e)
2286 (let ((labels (gen-labels ids))
2287 (new-vars (map gen-var ids)))
2288 (let ((w (make-binding-wrap ids labels w))
2289 (r (extend-var-env labels new-vars r)))
2291 (map syntax->datum ids)
2293 (map (lambda (x) (expand x r w mod)) #'(val ...))
2294 (expand-body #'(e1 e2 ...)
2295 (source-wrap e w s mod) r w mod)))))))
2296 (_ (syntax-violation 'letrec* "bad letrec*" (source-wrap e w s mod))))))
2301 (lambda (e r w s mod)
2306 (lambda () (resolve-identifier #'id w r mod #t))
2307 (lambda (type value id-mod)
2310 (build-lexical-assignment s (syntax->datum #'id) value
2311 (expand #'val r w mod)))
2313 (build-global-assignment s value (expand #'val r w mod) id-mod))
2315 (if (procedure-property value 'variable-transformer)
2316 ;; As syntax-type does, call expand-macro with
2317 ;; the mod of the expression. Hmm.
2318 (expand (expand-macro value e r w s #f mod) r empty-wrap mod)
2319 (syntax-violation 'set! "not a variable transformer"
2321 (wrap #'id w id-mod))))
2322 ((displaced-lexical)
2323 (syntax-violation 'set! "identifier out of context"
2326 (syntax-violation 'set! "bad set!" (source-wrap e w s mod)))))))
2327 ((_ (head tail ...) val)
2329 (lambda () (syntax-type #'head r empty-wrap no-source #f mod #t))
2330 (lambda (type value ee* ee ww ss modmod)
2333 (let ((val (expand #'val r w mod)))
2334 (call-with-values (lambda () (value #'(head tail ...) r w mod))
2335 (lambda (e r w s* mod)
2338 (build-global-assignment s (syntax->datum #'e)
2342 (expand #'(setter head) r w mod)
2343 (map (lambda (e) (expand e r w mod))
2344 #'(tail ... val))))))))
2345 (_ (syntax-violation 'set! "bad set!" (source-wrap e w s mod))))))
2347 (global-extend 'module-ref '@
2351 (and (and-map id? #'(mod ...)) (id? #'id))
2352 ;; Strip the wrap from the identifier and return top-wrap
2353 ;; so that the identifier will not be captured by lexicals.
2354 (values (syntax->datum #'id) r top-wrap #f
2356 #'(public mod ...)))))))
2358 (global-extend 'module-ref '@@
2363 (cons (remodulate (car x) mod)
2364 (remodulate (cdr x) mod)))
2367 (remodulate (syntax-object-expression x) mod)
2368 (syntax-object-wrap x)
2369 ;; hither the remodulation
2372 (let* ((n (vector-length x)) (v (make-vector n)))
2373 (do ((i 0 (fx+ i 1)))
2375 (vector-set! v i (remodulate (vector-ref x i) mod)))))
2377 (syntax-case e (@@ primitive)
2380 (equal? (cdr (if (syntax-object? #'id)
2381 (syntax-object-module #'id)
2384 ;; Strip the wrap from the identifier and return top-wrap
2385 ;; so that the identifier will not be captured by lexicals.
2386 (values (syntax->datum #'id) r top-wrap #f '(primitive)))
2388 (and (and-map id? #'(mod ...)) (id? #'id))
2389 ;; Strip the wrap from the identifier and return top-wrap
2390 ;; so that the identifier will not be captured by lexicals.
2391 (values (syntax->datum #'id) r top-wrap #f
2393 #'(private mod ...))))
2394 ((_ @@ (mod ...) exp)
2395 (and-map id? #'(mod ...))
2396 ;; This is a special syntax used to support R6RS library forms.
2397 ;; Unlike the syntax above, the last item is not restricted to
2398 ;; be a single identifier, and the syntax objects are kept
2399 ;; intact, with only their module changed.
2400 (let ((mod (syntax->datum #'(private mod ...))))
2401 (values (remodulate #'exp mod)
2402 r w (source-annotation #'exp)
2405 (global-extend 'core 'if
2406 (lambda (e r w s mod)
2411 (expand #'test r w mod)
2412 (expand #'then r w mod)
2413 (build-void no-source)))
2417 (expand #'test r w mod)
2418 (expand #'then r w mod)
2419 (expand #'else r w mod))))))
2421 (global-extend 'begin 'begin '())
2423 (global-extend 'define 'define '())
2425 (global-extend 'define-syntax 'define-syntax '())
2426 (global-extend 'define-syntax-parameter 'define-syntax-parameter '())
2428 (global-extend 'eval-when 'eval-when '())
2430 (global-extend 'core 'syntax-case
2432 (define convert-pattern
2433 ;; accepts pattern & keys
2434 ;; returns $sc-dispatch pattern & ids
2435 (lambda (pattern keys)
2438 (if (not (pair? p*))
2441 (lambda () (cvt* (cdr p*) n ids))
2444 (lambda () (cvt (car p*) n ids))
2446 (values (cons x y) ids))))))))
2448 (define (v-reverse x)
2449 (let loop ((r '()) (x x))
2452 (loop (cons (car x) r) (cdr x)))))
2458 ((bound-id-member? p keys)
2459 (values (vector 'free-id p) ids))
2463 (values 'any (cons (cons p n) ids))))
2466 (ellipsis? (syntax dots))
2468 (lambda () (cvt (syntax x) (fx+ n 1) ids))
2470 (values (if (eq? p 'any) 'each-any (vector 'each p))
2473 (ellipsis? (syntax dots))
2475 (lambda () (cvt* (syntax ys) n ids))
2478 (lambda () (cvt (syntax x) (+ n 1) ids))
2481 (lambda () (v-reverse ys))
2483 (values `#(each+ ,x ,ys ,e)
2487 (lambda () (cvt (syntax y) n ids))
2490 (lambda () (cvt (syntax x) n ids))
2492 (values (cons x y) ids))))))
2493 (() (values '() ids))
2496 (lambda () (cvt (syntax (x ...)) n ids))
2497 (lambda (p ids) (values (vector 'vector p) ids))))
2498 (x (values (vector 'atom (strip p empty-wrap)) ids))))))
2499 (cvt pattern 0 '())))
2501 (define build-dispatch-call
2502 (lambda (pvars exp y r mod)
2503 (let ((ids (map car pvars)) (levels (map cdr pvars)))
2504 (let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
2508 (list (build-simple-lambda no-source (map syntax->datum ids) #f new-vars '()
2512 (map (lambda (var level)
2513 (make-binding 'syntax `(,var . ,level)))
2517 (make-binding-wrap ids labels empty-wrap)
2522 (lambda (x keys clauses r pat fender exp mod)
2524 (lambda () (convert-pattern pat keys))
2527 ((not (distinct-bound-ids? (map car pvars)))
2528 (syntax-violation 'syntax-case "duplicate pattern variable" pat))
2529 ((not (and-map (lambda (x) (not (ellipsis? (car x)))) pvars))
2530 (syntax-violation 'syntax-case "misplaced ellipsis" pat))
2532 (let ((y (gen-var 'tmp)))
2533 ;; fat finger binding and references to temp variable y
2534 (build-call no-source
2535 (build-simple-lambda no-source (list 'tmp) #f (list y) '()
2536 (let ((y (build-lexical-reference 'value no-source
2538 (build-conditional no-source
2539 (syntax-case fender ()
2541 (_ (build-conditional no-source
2543 (build-dispatch-call pvars fender y r mod)
2544 (build-data no-source #f))))
2545 (build-dispatch-call pvars exp y r mod)
2546 (gen-syntax-case x keys clauses r mod))))
2547 (list (if (eq? p 'any)
2548 (build-primcall no-source 'list (list x))
2549 (build-primcall no-source '$sc-dispatch
2550 (list x (build-data no-source p)))))))))))))
2552 (define gen-syntax-case
2553 (lambda (x keys clauses r mod)
2555 (build-primcall no-source 'syntax-violation
2556 (list (build-data no-source #f)
2557 (build-data no-source
2558 "source expression failed to match any pattern")
2560 (syntax-case (car clauses) ()
2562 (if (and (id? #'pat)
2563 (and-map (lambda (x) (not (free-id=? #'pat x)))
2564 (cons #'(... ...) keys)))
2565 (if (free-id=? #'pat #'_)
2566 (expand #'exp r empty-wrap mod)
2567 (let ((labels (list (gen-label)))
2568 (var (gen-var #'pat)))
2569 (build-call no-source
2570 (build-simple-lambda
2571 no-source (list (syntax->datum #'pat)) #f (list var)
2575 (list (make-binding 'syntax `(,var . 0)))
2577 (make-binding-wrap #'(pat)
2581 (gen-clause x keys (cdr clauses) r
2582 #'pat #t #'exp mod)))
2584 (gen-clause x keys (cdr clauses) r
2585 #'pat #'fender #'exp mod))
2586 (_ (syntax-violation 'syntax-case "invalid clause"
2589 (lambda (e r w s mod)
2590 (let ((e (source-wrap e w s mod)))
2592 ((_ val (key ...) m ...)
2593 (if (and-map (lambda (x) (and (id? x) (not (ellipsis? x))))
2595 (let ((x (gen-var 'tmp)))
2596 ;; fat finger binding and references to temp variable x
2598 (build-simple-lambda no-source (list 'tmp) #f (list x) '()
2599 (gen-syntax-case (build-lexical-reference 'value no-source
2601 #'(key ...) #'(m ...)
2604 (list (expand #'val r empty-wrap mod))))
2605 (syntax-violation 'syntax-case "invalid literals list" e))))))))
2607 ;; The portable macroexpand seeds expand-top's mode m with 'e (for
2608 ;; evaluating) and esew (which stands for "eval syntax expanders
2609 ;; when") with '(eval). In Chez Scheme, m is set to 'c instead of e
2610 ;; if we are compiling a file, and esew is set to
2611 ;; (eval-syntactic-expanders-when), which defaults to the list
2612 ;; '(compile load eval). This means that, by default, top-level
2613 ;; syntactic definitions are evaluated immediately after they are
2614 ;; expanded, and the expanded definitions are also residualized into
2615 ;; the object file if we are compiling a file.
2617 (lambda* (x #:optional (m 'e) (esew '(eval)))
2618 (expand-top-sequence (list x) null-env top-wrap #f m esew
2619 (cons 'hygiene (module-name (current-module))))))
2627 (make-syntax-object datum (syntax-object-wrap id)
2628 (syntax-object-module id))))
2631 ;; accepts any object, since syntax objects may consist partially
2632 ;; or entirely of unwrapped, nonsymbolic data
2634 (strip x empty-wrap)))
2637 (lambda (x) (source-annotation x)))
2639 (set! generate-temporaries
2641 (arg-check list? ls 'generate-temporaries)
2642 (let ((mod (cons 'hygiene (module-name (current-module)))))
2643 (map (lambda (x) (wrap (gensym "t-") top-wrap mod)) ls))))
2645 (set! free-identifier=?
2647 (arg-check nonsymbol-id? x 'free-identifier=?)
2648 (arg-check nonsymbol-id? y 'free-identifier=?)
2651 (set! bound-identifier=?
2653 (arg-check nonsymbol-id? x 'bound-identifier=?)
2654 (arg-check nonsymbol-id? y 'bound-identifier=?)
2657 (set! syntax-violation
2658 (lambda* (who message form #:optional subform)
2659 (arg-check (lambda (x) (or (not x) (string? x) (symbol? x)))
2660 who 'syntax-violation)
2661 (arg-check string? message 'syntax-violation)
2662 (throw 'syntax-error who message
2663 (or (source-annotation subform)
2664 (source-annotation form))
2665 (strip form empty-wrap)
2666 (and subform (strip subform empty-wrap)))))
2669 (define (syntax-module id)
2670 (arg-check nonsymbol-id? id 'syntax-module)
2671 (let ((mod (syntax-object-module id)))
2672 (and (not (equal? mod '(primitive)))
2675 (define* (syntax-local-binding id #:key (resolve-syntax-parameters? #t))
2676 (arg-check nonsymbol-id? id 'syntax-local-binding)
2677 (with-transformer-environment
2678 (lambda (e r w s rib mod)
2679 (define (strip-anti-mark w)
2680 (let ((ms (wrap-marks w)) (s (wrap-subst w)))
2681 (if (and (pair? ms) (eq? (car ms) the-anti-mark))
2682 ;; output is from original text
2683 (make-wrap (cdr ms) (if rib (cons rib (cdr s)) (cdr s)))
2684 ;; output introduced by macro
2685 (make-wrap ms (if rib (cons rib s) s)))))
2686 (call-with-values (lambda ()
2688 (syntax-object-expression id)
2689 (strip-anti-mark (syntax-object-wrap id))
2691 (syntax-object-module id)
2692 resolve-syntax-parameters?))
2693 (lambda (type value mod)
2695 ((lexical) (values 'lexical value))
2696 ((macro) (values 'macro value))
2697 ((syntax-parameter) (values 'syntax-parameter (car value)))
2698 ((syntax) (values 'pattern-variable value))
2699 ((displaced-lexical) (values 'displaced-lexical #f))
2701 (if (equal? mod '(primitive))
2702 (values 'primitive value)
2703 (values 'global (cons value (cdr mod)))))
2704 (else (values 'other #f))))))))
2706 (define (syntax-locally-bound-identifiers id)
2707 (arg-check nonsymbol-id? id 'syntax-locally-bound-identifiers)
2708 (locally-bound-identifiers (syntax-object-wrap id)
2709 (syntax-object-module id)))
2711 ;; Using define! instead of set! to avoid warnings at
2712 ;; compile-time, after the variables are stolen away into (system
2713 ;; syntax). See the end of boot-9.scm.
2715 (define! 'syntax-module syntax-module)
2716 (define! 'syntax-local-binding syntax-local-binding)
2717 (define! 'syntax-locally-bound-identifiers syntax-locally-bound-identifiers))
2719 ;; $sc-dispatch expects an expression and a pattern. If the expression
2720 ;; matches the pattern a list of the matching expressions for each
2721 ;; "any" is returned. Otherwise, #f is returned. (This use of #f will
2722 ;; not work on r4rs implementations that violate the ieee requirement
2723 ;; that #f and () be distinct.)
2725 ;; The expression is matched with the pattern as follows:
2727 ;; pattern: matches:
2730 ;; (<pattern>1 . <pattern>2) (<pattern>1 . <pattern>2)
2732 ;; #(free-id <key>) <key> with free-identifier=?
2733 ;; #(each <pattern>) (<pattern>*)
2734 ;; #(each+ p1 (p2_1 ... p2_n) p3) (p1* (p2_n ... p2_1) . p3)
2735 ;; #(vector <pattern>) (list->vector <pattern>)
2736 ;; #(atom <object>) <object> with "equal?"
2738 ;; Vector cops out to pair under assumption that vectors are rare. If
2739 ;; not, should convert to:
2740 ;; #(vector <pattern>*) #(<pattern>*)
2748 (let ((first (match (car e) p w '() mod)))
2750 (let ((rest (match-each (cdr e) p w mod)))
2751 (and rest (cons first rest))))))
2754 (match-each (syntax-object-expression e)
2756 (join-wraps w (syntax-object-wrap e))
2757 (syntax-object-module e)))
2761 (lambda (e x-pat y-pat z-pat w r mod)
2762 (let f ((e e) (w w))
2765 (call-with-values (lambda () (f (cdr e) w))
2766 (lambda (xr* y-pat r)
2769 (let ((xr (match (car e) x-pat w '() mod)))
2771 (values (cons xr xr*) y-pat r)
2776 (match (car e) (car y-pat) w r mod)))
2777 (values #f #f #f)))))
2779 (f (syntax-object-expression e) (join-wraps w e)))
2781 (values '() y-pat (match e z-pat w r mod)))))))
2783 (define match-each-any
2787 (let ((l (match-each-any (cdr e) w mod)))
2788 (and l (cons (wrap (car e) w mod) l))))
2791 (match-each-any (syntax-object-expression e)
2792 (join-wraps w (syntax-object-wrap e))
2801 ((eq? p 'any) (cons '() r))
2802 ((pair? p) (match-empty (car p) (match-empty (cdr p) r)))
2803 ((eq? p 'each-any) (cons '() r))
2805 (case (vector-ref p 0)
2806 ((each) (match-empty (vector-ref p 1) r))
2807 ((each+) (match-empty (vector-ref p 1)
2809 (reverse (vector-ref p 2))
2810 (match-empty (vector-ref p 3) r))))
2812 ((vector) (match-empty (vector-ref p 1) r)))))))
2816 (if (null? (car r*))
2818 (cons (map car r*) (combine (map cdr r*) r)))))
2821 (lambda (e p w r mod)
2823 ((null? p) (and (null? e) r))
2825 (and (pair? e) (match (car e) (car p) w
2826 (match (cdr e) (cdr p) w r mod)
2829 (let ((l (match-each-any e w mod))) (and l (cons l r))))
2831 (case (vector-ref p 0)
2834 (match-empty (vector-ref p 1) r)
2835 (let ((l (match-each e (vector-ref p 1) w mod)))
2837 (let collect ((l l))
2840 (cons (map car l) (collect (map cdr l)))))))))
2844 (match-each+ e (vector-ref p 1) (vector-ref p 2) (vector-ref p 3) w r mod))
2845 (lambda (xr* y-pat r)
2849 (match-empty (vector-ref p 1) r)
2850 (combine xr* r))))))
2851 ((free-id) (and (id? e) (free-id=? (wrap e w mod) (vector-ref p 1)) r))
2852 ((atom) (and (equal? (vector-ref p 1) (strip e w)) r))
2855 (match (vector->list e) (vector-ref p 1) w r mod))))))))
2858 (lambda (e p w r mod)
2862 ((eq? p 'any) (cons (wrap e w mod) r))
2865 (syntax-object-expression e)
2867 (join-wraps w (syntax-object-wrap e))
2869 (syntax-object-module e)))
2870 (else (match* e p w r mod)))))
2875 ((eq? p 'any) (list e))
2878 (match* (syntax-object-expression e)
2879 p (syntax-object-wrap e) '() (syntax-object-module e)))
2880 (else (match* e p empty-wrap '() #f))))))))
2883 (define-syntax with-syntax
2887 #'(let () e1 e2 ...))
2888 ((_ ((out in)) e1 e2 ...)
2889 #'(syntax-case in ()
2890 (out (let () e1 e2 ...))))
2891 ((_ ((out in) ...) e1 e2 ...)
2892 #'(syntax-case (list in ...) ()
2893 ((out ...) (let () e1 e2 ...)))))))
2895 (define-syntax syntax-rules
2898 ((_ (k ...) ((keyword . pattern) template) ...)
2900 ;; embed patterns as procedure metadata
2901 #((macro-type . syntax-rules)
2902 (patterns pattern ...))
2903 (syntax-case x (k ...)
2904 ((_ . pattern) #'template)
2906 ((_ (k ...) docstring ((keyword . pattern) template) ...)
2907 (string? (syntax->datum #'docstring))
2909 ;; the same, but allow a docstring
2911 #((macro-type . syntax-rules)
2912 (patterns pattern ...))
2913 (syntax-case x (k ...)
2914 ((_ . pattern) #'template)
2917 (define-syntax define-syntax-rule
2920 ((_ (name . pattern) template)
2921 #'(define-syntax name
2923 ((_ . pattern) template))))
2924 ((_ (name . pattern) docstring template)
2925 (string? (syntax->datum #'docstring))
2926 #'(define-syntax name
2929 ((_ . pattern) template)))))))
2934 ((let* ((x v) ...) e1 e2 ...)
2935 (and-map identifier? #'(x ...))
2936 (let f ((bindings #'((x v) ...)))
2937 (if (null? bindings)
2938 #'(let () e1 e2 ...)
2939 (with-syntax ((body (f (cdr bindings)))
2940 (binding (car bindings)))
2941 #'(let (binding) body))))))))
2943 (define-syntax quasiquote
2945 (define (quasi p lev)
2946 (syntax-case p (unquote quasiquote)
2950 (quasicons #'("quote" unquote) (quasi #'(p) (- lev 1)))))
2951 ((quasiquote p) (quasicons #'("quote" quasiquote) (quasi #'(p) (+ lev 1))))
2953 (syntax-case #'p (unquote unquote-splicing)
2956 (quasilist* #'(("value" p) ...) (quasi #'q lev))
2958 (quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
2960 ((unquote-splicing p ...)
2962 (quasiappend #'(("value" p) ...) (quasi #'q lev))
2964 (quasicons #'("quote" unquote-splicing) (quasi #'(p ...) (- lev 1)))
2966 (_ (quasicons (quasi #'p lev) (quasi #'q lev)))))
2967 (#(x ...) (quasivector (vquasi #'(x ...) lev)))
2969 (define (vquasi p lev)
2972 (syntax-case #'p (unquote unquote-splicing)
2975 (quasilist* #'(("value" p) ...) (vquasi #'q lev))
2977 (quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
2979 ((unquote-splicing p ...)
2981 (quasiappend #'(("value" p) ...) (vquasi #'q lev))
2984 #'("quote" unquote-splicing)
2985 (quasi #'(p ...) (- lev 1)))
2987 (_ (quasicons (quasi #'p lev) (vquasi #'q lev)))))
2988 (() #'("quote" ()))))
2989 (define (quasicons x y)
2990 (with-syntax ((x x) (y y))
2994 (("quote" dx) #'("quote" (dx . dy)))
2995 (_ (if (null? #'dy) #'("list" x) #'("list*" x y)))))
2996 (("list" . stuff) #'("list" x . stuff))
2997 (("list*" . stuff) #'("list*" x . stuff))
2998 (_ #'("list*" x y)))))
2999 (define (quasiappend x y)
3003 ((null? x) #'("quote" ()))
3004 ((null? (cdr x)) (car x))
3005 (else (with-syntax (((p ...) x)) #'("append" p ...)))))
3009 (else (with-syntax (((p ...) x) (y y)) #'("append" p ... y)))))))
3010 (define (quasilist* x y)
3014 (quasicons (car x) (f (cdr x))))))
3015 (define (quasivector x)
3017 (("quote" (x ...)) #'("quote" #(x ...)))
3019 (let f ((y x) (k (lambda (ls) #`("vector" #,@ls))))
3021 (("quote" (y ...)) (k #'(("quote" y) ...)))
3022 (("list" y ...) (k #'(y ...)))
3023 (("list*" y ... z) (f #'z (lambda (ls) (k (append #'(y ...) ls)))))
3024 (else #`("list->vector" #,x)))))))
3028 (("list" x ...) #`(list #,@(map emit #'(x ...))))
3029 ;; could emit list* for 3+ arguments if implementation supports
3032 (let f ((x* #'(x ...)))
3035 #`(cons #,(emit (car x*)) #,(f (cdr x*))))))
3036 (("append" x ...) #`(append #,@(map emit #'(x ...))))
3037 (("vector" x ...) #`(vector #,@(map emit #'(x ...))))
3038 (("list->vector" x) #`(list->vector #,(emit #'x)))
3042 ;; convert to intermediate language, combining introduced (but
3043 ;; not unquoted source) quote expressions where possible and
3044 ;; choosing optimal construction code otherwise, then emit
3045 ;; Scheme code corresponding to the intermediate language forms.
3046 ((_ e) (emit (quasi #'e 0)))))))
3048 (define-syntax include
3052 (let* ((p (open-input-file
3053 (if (absolute-file-name? fn)
3055 (in-vicinity dir fn))))
3056 (enc (file-encoding p)))
3058 ;; Choose the input encoding deterministically.
3059 (set-port-encoding! p (or enc "UTF-8"))
3061 (let f ((x (read p))
3065 (close-input-port p)
3068 (cons (datum->syntax k x) result)))))))
3069 (let* ((src (syntax-source x))
3070 (file (and src (assq-ref src 'filename)))
3071 (dir (and (string? file) (dirname file))))
3074 (let ((fn (syntax->datum #'filename)))
3075 (with-syntax (((exp ...) (read-file fn dir #'filename)))
3076 #'(begin exp ...))))))))
3078 (define-syntax include-from-path
3082 (let ((fn (syntax->datum #'filename)))
3083 (with-syntax ((fn (datum->syntax
3085 (or (%search-load-path fn)
3086 (syntax-violation 'include-from-path
3087 "file not found in path"
3089 #'(include fn)))))))
3091 (define-syntax unquote
3093 (syntax-violation 'unquote
3094 "expression not valid outside of quasiquote"
3097 (define-syntax unquote-splicing
3099 (syntax-violation 'unquote-splicing
3100 "expression not valid outside of quasiquote"
3103 (define (make-variable-transformer proc)
3104 (if (procedure? proc)
3105 (let ((trans (lambda (x)
3106 #((macro-type . variable-transformer))
3108 (set-procedure-property! trans 'variable-transformer #t)
3110 (error "variable transformer not a procedure" proc)))
3112 (define-syntax identifier-syntax
3114 (syntax-case xx (set!)
3117 #((macro-type . identifier-syntax))
3123 #'(e x (... ...))))))
3124 ((_ (id exp1) ((set! var val) exp2))
3125 (and (identifier? #'id) (identifier? #'var))
3126 #'(make-variable-transformer
3128 #((macro-type . variable-transformer))
3129 (syntax-case x (set!)
3130 ((set! var val) #'exp2)
3131 ((id x (... ...)) #'(exp1 x (... ...)))
3132 (id (identifier? #'id) #'exp1))))))))
3134 (define-syntax define*
3137 ((_ (id . args) b0 b1 ...)
3138 #'(define id (lambda* args b0 b1 ...)))
3139 ((_ id val) (identifier? #'id)
3140 #'(define id val)))))