3 ;;;; Copyright (C) 2001, 2003, 2006, 2009, 2010 Free Software Foundation, Inc.
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.
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.
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
21 ;;; Portable implementation of syntax-case
22 ;;; Extracted from Chez Scheme Version 5.9f
23 ;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
25 ;;; Modified by Andy Wingo <wingo@pobox.com> according to the Git
26 ;;; revision control logs corresponding to this file: 2009.
28 ;;; Modified by Mikael Djurfeldt <djurfeldt@nada.kth.se> according
29 ;;; to the ChangeLog distributed in the same directory as this file:
30 ;;; 1997-08-19, 1997-09-03, 1997-09-10, 2000-08-13, 2000-08-24,
31 ;;; 2000-09-12, 2001-03-08
33 ;;; Copyright (c) 1992-1997 Cadence Research Systems
34 ;;; Permission to copy this software, in whole or in part, to use this
35 ;;; software for any lawful purpose, and to redistribute this software
36 ;;; is granted subject to the restriction that all copies made of this
37 ;;; software must include this copyright notice in full. This software
38 ;;; is provided AS IS, with NO WARRANTY, EITHER EXPRESS OR IMPLIED,
39 ;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
40 ;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
41 ;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
42 ;;; NATURE WHATSOEVER.
44 ;;; Before attempting to port this code to a new implementation of
45 ;;; Scheme, please read the notes below carefully.
48 ;;; This file defines the syntax-case expander, macroexpand, and a set
49 ;;; of associated syntactic forms and procedures. Of these, the
50 ;;; following are documented in The Scheme Programming Language,
51 ;;; Second Edition (R. Kent Dybvig, Prentice Hall, 1996). Most are
52 ;;; also documented in the R4RS and draft R5RS.
54 ;;; bound-identifier=?
59 ;;; generate-temporaries
70 ;;; All standard Scheme syntactic forms are supported by the expander
71 ;;; or syntactic abstractions defined in this file. Only the R4RS
72 ;;; delay is omitted, since its expansion is implementation-dependent.
74 ;;; The remaining exports are listed below:
76 ;;; (macroexpand datum)
77 ;;; if datum represents a valid expression, macroexpand returns an
78 ;;; expanded version of datum in a core language that includes no
79 ;;; syntactic abstractions. The core language includes begin,
80 ;;; define, if, lambda, letrec, quote, and set!.
81 ;;; (eval-when situations expr ...)
82 ;;; conditionally evaluates expr ... at compile-time or run-time
83 ;;; depending upon situations (see the Chez Scheme System Manual,
84 ;;; Revision 3, for a complete description)
85 ;;; (syntax-violation who message form [subform])
86 ;;; used to report errors found during expansion
87 ;;; ($sc-dispatch e p)
88 ;;; used by expanded code to handle syntax-case matching
90 ;;; The following nonstandard procedures must be provided by the
91 ;;; implementation for this code to run using the standard portable
92 ;;; hooks and output constructors. They are not used by expanded code,
93 ;;; and so need be present only at expansion time.
96 ;;; where x is always in the form ("noexpand" expr).
97 ;;; returns the value of expr. the "noexpand" flag is used to tell the
98 ;;; evaluator/expander that no expansion is necessary, since expr has
99 ;;; already been fully expanded to core forms.
101 ;;; eval will not be invoked during the loading of psyntax.pp. After
102 ;;; psyntax.pp has been loaded, the expansion of any macro definition,
103 ;;; whether local or global, will result in a call to eval. If, however,
104 ;;; macroexpand has already been registered as the expander to be used
105 ;;; by eval, and eval accepts one argument, nothing special must be done
106 ;;; to support the "noexpand" flag, since it is handled by macroexpand.
109 ;;; returns a unique symbol each time it's called
111 ;;; When porting to a new Scheme implementation, you should define the
112 ;;; procedures listed above, load the expanded version of psyntax.ss
113 ;;; (psyntax.pp, which should be available whereever you found
114 ;;; psyntax.ss), and register macroexpand as the current expander (how
115 ;;; you do this depends upon your implementation of Scheme). You may
116 ;;; change the hooks and constructors defined toward the beginning of
117 ;;; the code below, but to avoid bootstrapping problems, do so only
118 ;;; after you have a working version of the expander.
120 ;;; Chez Scheme allows the syntactic form (syntax <template>) to be
121 ;;; abbreviated to #'<template>, just as (quote <datum>) may be
122 ;;; abbreviated to '<datum>. The #' syntax makes programs written
123 ;;; using syntax-case shorter and more readable and draws out the
124 ;;; intuitive connection between syntax and quote.
126 ;;; If you find that this code loads or runs slowly, consider
127 ;;; switching to faster hardware or a faster implementation of
128 ;;; Scheme. In Chez Scheme on a 200Mhz Pentium Pro, expanding,
129 ;;; compiling (with full optimization), and loading this file takes
130 ;;; between one and two seconds.
132 ;;; In the expander implementation, we sometimes use syntactic abstractions
133 ;;; when procedural abstractions would suffice. For example, we define
134 ;;; top-wrap and top-marked? as
135 ;;; (define-syntax top-wrap (identifier-syntax '((top))))
136 ;;; (define-syntax top-marked?
138 ;;; ((_ w) (memq 'top (wrap-marks w)))))
140 ;;; (define top-wrap '((top)))
141 ;;; (define top-marked?
142 ;;; (lambda (w) (memq 'top (wrap-marks w))))
143 ;;; On ther other hand, we don't do this consistently; we define make-wrap,
144 ;;; wrap-marks, and wrap-subst simply as
145 ;;; (define make-wrap cons)
146 ;;; (define wrap-marks car)
147 ;;; (define wrap-subst cdr)
148 ;;; In Chez Scheme, the syntactic and procedural forms of these
149 ;;; abstractions are equivalent, since the optimizer consistently
150 ;;; integrates constants and small procedures. Some Scheme
151 ;;; implementations, however, may benefit from more consistent use
152 ;;; of one form or the other.
155 ;;; implementation information:
157 ;;; "begin" is treated as a splicing construct at top level and at
158 ;;; the beginning of bodies. Any sequence of expressions that would
159 ;;; be allowed where the "begin" occurs is allowed.
161 ;;; "let-syntax" and "letrec-syntax" are also treated as splicing
162 ;;; constructs, in violation of the R4RS appendix and probably the R5RS
163 ;;; when it comes out. A consequence, let-syntax and letrec-syntax do
164 ;;; not create local contours, as do let and letrec. Although the
165 ;;; functionality is greater as it is presently implemented, we will
166 ;;; probably change it to conform to the R4RS/expected R5RS.
168 ;;; Objects with no standard print syntax, including objects containing
169 ;;; cycles and syntax object, are allowed in quoted data as long as they
170 ;;; are contained within a syntax form or produced by datum->syntax.
171 ;;; Such objects are never copied.
173 ;;; All identifiers that don't have macro definitions and are not bound
174 ;;; lexically are assumed to be global variables
176 ;;; Top-level definitions of macro-introduced identifiers are allowed.
177 ;;; This may not be appropriate for implementations in which the
178 ;;; model is that bindings are created by definitions, as opposed to
179 ;;; one in which initial values are assigned by definitions.
181 ;;; Top-level variable definitions of syntax keywords is not permitted.
182 ;;; Any solution allowing this would be kludgey and would yield
183 ;;; surprising results in some cases. We can provide an undefine-syntax
184 ;;; form. The questions is, should define be an implicit undefine-syntax?
185 ;;; We've decided no for now.
187 ;;; Identifiers and syntax objects are implemented as vectors for
188 ;;; portability. As a result, it is possible to "forge" syntax
191 ;;; The implementation of generate-temporaries assumes that it is possible
192 ;;; to generate globally unique symbols (gensyms).
197 ;;; When changing syntax-object representations, it is necessary to support
198 ;;; both old and new syntax-object representations in id-var-name. It
199 ;;; should be sufficient to recognize old representations and treat
200 ;;; them as not lexically bound.
205 (set-current-module (resolve-module '(guile))))
208 ;;; Private version of and-map that handles multiple lists.
210 (lambda (f first . rest)
213 (let andmap ((first first))
214 (let ((x (car first)) (first (cdr first)))
217 (and (f x) (andmap first)))))
218 (let andmap ((first first) (rest rest))
219 (let ((x (car first))
222 (rest (map cdr rest)))
224 (apply f (cons x xr))
225 (and (apply f (cons x xr)) (andmap first rest)))))))))
227 (define-syntax define-structure
229 (define construct-name
230 (lambda (template-identifier . args)
238 (symbol->string (syntax->datum x))))
242 (and-map identifier? #'(name id1 ...))
244 ((constructor (construct-name #'name "make-" #'name))
245 (predicate (construct-name #'name #'name "?"))
247 (map (lambda (x) (construct-name x #'name "-" x))
251 (construct-name x "set-" #'name "-" x "!"))
254 (+ (length #'(id1 ...)) 1))
256 (let f ((i 1) (ids #'(id1 ...)))
259 (cons i (f (+ i 1) (cdr ids)))))))
263 (vector 'name id1 ... )))
267 (= (vector-length x) structure-length)
268 (eq? (vector-ref x 0) 'name))))
271 (vector-ref x index)))
275 (vector-set! x index update)))
279 (define noexpand "noexpand")
280 (define *mode* (make-fluid))
282 ;;; hooks to nonportable run-time helpers
289 (define top-level-eval-hook
293 ,(case (fluid-ref *mode*)
294 ((c) ((@ (language tree-il) tree-il->scheme) x))
297 (define local-eval-hook
301 ,(case (fluid-ref *mode*)
302 ((c) ((@ (language tree-il) tree-il->scheme) x))
305 (define-syntax gensym-hook
309 (define put-global-definition-hook
310 (lambda (symbol type val)
311 (module-define! (current-module)
313 (make-syntax-transformer symbol type val))))
315 (define get-global-definition-hook
316 (lambda (symbol module)
317 (if (and (not module) (current-module))
318 (warn "module system is booted, we should have a module" symbol))
319 (let ((v (module-variable (if module
320 (resolve-module (cdr module))
323 (and v (variable-bound? v)
324 (let ((val (variable-ref v)))
325 (and (macro? val) (macro-type val)
326 (cons (macro-type val)
327 (macro-binding val))))))))
332 (define (decorate-source e s)
333 (if (and (pair? e) s)
334 (set-source-properties! e s))
337 ;;; output constructors
340 (case (fluid-ref *mode*)
341 ((c) ((@ (language tree-il) make-void) source))
342 (else (decorate-source '(if #f #f) source)))))
344 (define build-application
345 (lambda (source fun-exp arg-exps)
346 (case (fluid-ref *mode*)
347 ((c) ((@ (language tree-il) make-application) source fun-exp arg-exps))
348 (else (decorate-source `(,fun-exp . ,arg-exps) source)))))
350 (define build-conditional
351 (lambda (source test-exp then-exp else-exp)
352 (case (fluid-ref *mode*)
353 ((c) ((@ (language tree-il) make-conditional)
354 source test-exp then-exp else-exp))
355 (else (decorate-source
356 (if (equal? else-exp '(if #f #f))
357 `(if ,test-exp ,then-exp)
358 `(if ,test-exp ,then-exp ,else-exp))
362 (lambda (source fluids vals body)
363 (case (fluid-ref *mode*)
364 ((c) ((@ (language tree-il) make-dynlet) source fluids vals body))
365 (else (decorate-source `(with-fluids ,(map list fluids vals) ,body)
368 (define build-lexical-reference
369 (lambda (type source name var)
370 (case (fluid-ref *mode*)
371 ((c) ((@ (language tree-il) make-lexical-ref) source name var))
372 (else (decorate-source var source)))))
374 (define build-lexical-assignment
375 (lambda (source name var exp)
376 (case (fluid-ref *mode*)
377 ((c) ((@ (language tree-il) make-lexical-set) source name var exp))
378 (else (decorate-source `(set! ,var ,exp) source)))))
380 ;; Before modules are booted, we can't expand into data structures from
381 ;; (language tree-il) -- we need to give the evaluator the
382 ;; s-expressions that it understands natively. Actually the real truth
383 ;; of the matter is that the evaluator doesn't understand tree-il
384 ;; structures at all. So until we fix the evaluator, if ever, the
385 ;; conflation that we should use tree-il iff we are compiling
388 (define (analyze-variable mod var modref-cont bare-cont)
391 (let ((kind (car mod))
394 ((public) (modref-cont mod var #t))
395 ((private) (if (not (equal? mod (module-name (current-module))))
396 (modref-cont mod var #f)
398 ((bare) (bare-cont var))
399 ((hygiene) (if (and (not (equal? mod (module-name (current-module))))
400 (module-variable (resolve-module mod) var))
401 (modref-cont mod var #f)
403 (else (syntax-violation #f "bad module kind" var mod))))))
405 (define build-global-reference
406 (lambda (source var mod)
409 (lambda (mod var public?)
410 (case (fluid-ref *mode*)
411 ((c) ((@ (language tree-il) make-module-ref) source mod var public?))
412 (else (decorate-source (list (if public? '@ '@@) mod var) source))))
414 (case (fluid-ref *mode*)
415 ((c) ((@ (language tree-il) make-toplevel-ref) source var))
416 (else (decorate-source var source)))))))
418 (define build-global-assignment
419 (lambda (source var exp mod)
422 (lambda (mod var public?)
423 (case (fluid-ref *mode*)
424 ((c) ((@ (language tree-il) make-module-set) source mod var public? exp))
425 (else (decorate-source `(set! ,(list (if public? '@ '@@) mod var) ,exp) source))))
427 (case (fluid-ref *mode*)
428 ((c) ((@ (language tree-il) make-toplevel-set) source var exp))
429 (else (decorate-source `(set! ,var ,exp) source)))))))
431 ;; FIXME: there is a bug that prevents (set! ((@ (foo) bar) baz) quz)
432 ;; from working. Hack around it.
433 (define (maybe-name-value! name val)
435 (((@ (language tree-il) lambda?) val)
436 (let ((meta ((@ (language tree-il) lambda-meta) val)))
437 (if (not (assq 'name meta))
438 ((setter (@ (language tree-il) lambda-meta))
440 (acons 'name name meta)))))))
442 (define build-global-definition
443 (lambda (source var exp)
444 (case (fluid-ref *mode*)
446 (maybe-name-value! var exp)
447 ((@ (language tree-il) make-toplevel-define) source var exp))
448 (else (decorate-source `(define ,var ,exp) source)))))
450 ;; Ideally we would have all lambdas be case lambdas, but that would
451 ;; need special support in the interpreter for the full capabilities
452 ;; of case-lambda, with optional and keyword args and else clauses.
453 ;; This will come with the new interpreter, but for now we separate
455 (define build-simple-lambda
456 (lambda (src req rest vars meta exp)
457 (case (fluid-ref *mode*)
458 ((c) ((@ (language tree-il) make-lambda) src
460 ;; hah, a case in which kwargs would be nice.
461 ((@ (language tree-il) make-lambda-case)
462 ;; src req opt rest kw inits vars body else
463 src req #f rest #f '() vars exp #f)))
464 (else (decorate-source
465 `(lambda ,(if rest (apply cons* vars) vars)
468 (define build-case-lambda
469 (lambda (src meta body)
470 (case (fluid-ref *mode*)
471 ((c) ((@ (language tree-il) make-lambda) src
474 (else (decorate-source
480 (define build-lambda-case
482 ;; opt := (name ...) | #f
484 ;; kw := (allow-other-keys? (keyword name var [init]) ...) | #f
487 ;; vars map to named arguments in the following order:
488 ;; required, optional (positional), rest, keyword.
489 ;; the body of a lambda: anything, already expanded
490 ;; else: lambda-case | #f
491 (lambda (src req opt rest kw inits vars body else-case)
492 (case (fluid-ref *mode*)
494 ((@ (language tree-il) make-lambda-case)
495 src req opt rest kw inits vars body else-case))
497 ;; Very much like the logic of (language tree-il compile-glil).
498 (let* ((nreq (length req))
499 (nopt (if opt (length opt) 0))
500 (rest-idx (and rest (+ nreq nopt)))
501 (allow-other-keys? (if kw (car kw) #f))
502 (kw-indices (map (lambda (x)
504 (cons (car x) (list-index vars (caddr x))))
505 (if kw (cdr kw) '())))
506 (nargs (apply max (+ nreq nopt (if rest 1 0))
507 (map 1+ (map cdr kw-indices)))))
510 (+ nreq (length inits) (if rest 1 0)))
511 (error "something went wrong"
512 req opt rest kw inits vars nreq nopt kw-indices nargs))
514 `((((@@ (ice-9 optargs) parse-lambda-case)
515 '(,nreq ,nopt ,rest-idx ,nargs ,allow-other-keys? ,kw-indices)
516 (list ,@(map (lambda (i) `(lambda ,vars ,i)) inits))
518 => (lambda (%%args) (apply (lambda ,vars ,body) %%args)))
520 `((%%args (scm-error 'wrong-number-of-args #f
521 "Wrong number of arguments" '()
525 (define build-primref
527 (if (equal? (module-name (current-module)) '(guile))
528 (case (fluid-ref *mode*)
529 ((c) ((@ (language tree-il) make-toplevel-ref) src name))
530 (else (decorate-source name src)))
531 (case (fluid-ref *mode*)
532 ((c) ((@ (language tree-il) make-module-ref) src '(guile) name #f))
533 (else (decorate-source `(@@ (guile) ,name) src))))))
535 (define (build-data src exp)
536 (case (fluid-ref *mode*)
537 ((c) ((@ (language tree-il) make-const) src exp))
538 (else (decorate-source
539 (if (and (self-evaluating? exp) (not (vector? exp)))
544 (define build-sequence
546 (if (null? (cdr exps))
548 (case (fluid-ref *mode*)
549 ((c) ((@ (language tree-il) make-sequence) src exps))
550 (else (decorate-source `(begin ,@exps) src))))))
553 (lambda (src ids vars val-exps body-exp)
556 (case (fluid-ref *mode*)
558 (for-each maybe-name-value! ids val-exps)
559 ((@ (language tree-il) make-let) src ids vars val-exps body-exp))
560 (else (decorate-source
561 `(let ,(map list vars val-exps) ,body-exp)
564 (define build-named-let
565 (lambda (src ids vars val-exps body-exp)
570 (case (fluid-ref *mode*)
572 (let ((proc (build-simple-lambda src ids #f vars '() body-exp)))
573 (maybe-name-value! f-name proc)
574 (for-each maybe-name-value! ids val-exps)
575 ((@ (language tree-il) make-letrec) src
576 (list f-name) (list f) (list proc)
577 (build-application src (build-lexical-reference 'fun src f-name f)
579 (else (decorate-source
580 `(letrec ((,f (lambda ,vars ,body-exp)))
585 (lambda (src ids vars val-exps body-exp)
588 (case (fluid-ref *mode*)
590 (for-each maybe-name-value! ids val-exps)
591 ((@ (language tree-il) make-letrec) src ids vars val-exps body-exp))
592 (else (decorate-source
593 `(letrec ,(map list vars val-exps) ,body-exp)
596 ;; FIXME: use a faster gensym
597 (define-syntax build-lexical-var
599 ((_ src id) (gensym (string-append (symbol->string id) " ")))))
601 (define-structure (syntax-object expression wrap module))
603 (define-syntax no-source (identifier-syntax #f))
605 (define source-annotation
609 (source-annotation (syntax-object-expression x)))
610 ((pair? x) (let ((props (source-properties x)))
616 (define-syntax arg-check
620 (if (not (pred? x)) (syntax-violation who "invalid argument" x))))))
622 ;;; compile-time environments
624 ;;; wrap and environment comprise two level mapping.
625 ;;; wrap : id --> label
626 ;;; env : label --> <element>
628 ;;; environments are represented in two parts: a lexical part and a global
629 ;;; part. The lexical part is a simple list of associations from labels
630 ;;; to bindings. The global part is implemented by
631 ;;; {put,get}-global-definition-hook and associates symbols with
634 ;;; global (assumed global variable) and displaced-lexical (see below)
635 ;;; do not show up in any environment; instead, they are fabricated by
636 ;;; lookup when it finds no other bindings.
638 ;;; <environment> ::= ((<label> . <binding>)*)
640 ;;; identifier bindings include a type and a value
642 ;;; <binding> ::= (macro . <procedure>) macros
643 ;;; (core . <procedure>) core forms
644 ;;; (module-ref . <procedure>) @ or @@
647 ;;; (define-syntax) define-syntax
648 ;;; (local-syntax . rec?) let-syntax/letrec-syntax
649 ;;; (eval-when) eval-when
650 ;;; #'. (<var> . <level>) pattern variables
651 ;;; (global) assumed global variable
652 ;;; (lexical . <var>) lexical variables
653 ;;; (displaced-lexical) displaced lexicals
654 ;;; <level> ::= <nonnegative integer>
655 ;;; <var> ::= variable returned by build-lexical-var
657 ;;; a macro is a user-defined syntactic-form. a core is a system-defined
658 ;;; syntactic form. begin, define, define-syntax, and eval-when are
659 ;;; treated specially since they are sensitive to whether the form is
660 ;;; at top-level and (except for eval-when) can denote valid internal
663 ;;; a pattern variable is a variable introduced by syntax-case and can
664 ;;; be referenced only within a syntax form.
666 ;;; any identifier for which no top-level syntax definition or local
667 ;;; binding of any kind has been seen is assumed to be a global
670 ;;; a lexical variable is a lambda- or letrec-bound variable.
672 ;;; a displaced-lexical identifier is a lexical identifier removed from
673 ;;; it's scope by the return of a syntax object containing the identifier.
674 ;;; a displaced lexical can also appear when a letrec-syntax-bound
675 ;;; keyword is referenced on the rhs of one of the letrec-syntax clauses.
676 ;;; a displaced lexical should never occur with properly written macros.
678 (define-syntax make-binding
679 (syntax-rules (quote)
680 ((_ type value) (cons type value))
682 ((_ type) (cons type '()))))
683 (define binding-type car)
684 (define binding-value cdr)
686 (define-syntax null-env (identifier-syntax '()))
689 (lambda (labels bindings r)
692 (extend-env (cdr labels) (cdr bindings)
693 (cons (cons (car labels) (car bindings)) r)))))
695 (define extend-var-env
696 ; variant of extend-env that forms "lexical" binding
697 (lambda (labels vars r)
700 (extend-var-env (cdr labels) (cdr vars)
701 (cons (cons (car labels) (make-binding 'lexical (car vars))) r)))))
703 ;;; we use a "macros only" environment in expansion of local macro
704 ;;; definitions so that their definitions can use local macros without
705 ;;; attempting to use other lexical identifiers.
706 (define macros-only-env
711 (if (eq? (cadr a) 'macro)
712 (cons a (macros-only-env (cdr r)))
713 (macros-only-env (cdr r)))))))
716 ; x may be a label or a symbol
717 ; although symbols are usually global, we check the environment first
718 ; anyway because a temporary binding may have been established by
724 (or (get-global-definition-hook x mod) (make-binding 'global)))
725 (else (make-binding 'displaced-lexical)))))
727 (define global-extend
728 (lambda (type sym val)
729 (put-global-definition-hook sym type val)))
732 ;;; Conceptually, identifiers are always syntax objects. Internally,
733 ;;; however, the wrap is sometimes maintained separately (a source of
734 ;;; efficiency and confusion), so that symbols are also considered
735 ;;; identifiers by id?. Externally, they are always wrapped.
737 (define nonsymbol-id?
739 (and (syntax-object? x)
740 (symbol? (syntax-object-expression x)))))
746 ((syntax-object? x) (symbol? (syntax-object-expression x)))
749 (define-syntax id-sym-name
753 (if (syntax-object? x)
754 (syntax-object-expression x)
757 (define id-sym-name&marks
759 (if (syntax-object? x)
761 (syntax-object-expression x)
762 (join-marks (wrap-marks w) (wrap-marks (syntax-object-wrap x))))
763 (values x (wrap-marks w)))))
765 ;;; syntax object wraps
767 ;;; <wrap> ::= ((<mark> ...) . (<subst> ...))
768 ;;; <subst> ::= <shift> | <subs>
769 ;;; <subs> ::= #(<old name> <label> (<mark> ...))
770 ;;; <shift> ::= positive fixnum
772 (define make-wrap cons)
773 (define wrap-marks car)
774 (define wrap-subst cdr)
776 (define-syntax subst-rename? (identifier-syntax vector?))
777 (define-syntax rename-old (syntax-rules () ((_ x) (vector-ref x 0))))
778 (define-syntax rename-new (syntax-rules () ((_ x) (vector-ref x 1))))
779 (define-syntax rename-marks (syntax-rules () ((_ x) (vector-ref x 2))))
780 (define-syntax make-rename
782 ((_ old new marks) (vector old new marks))))
784 ;;; labels must be comparable with "eq?", have read-write invariance,
785 ;;; and distinct from symbols.
787 (lambda () (symbol->string (gensym "i"))))
793 (cons (gen-label) (gen-labels (cdr ls))))))
795 (define-structure (ribcage symnames marks labels))
797 (define-syntax empty-wrap (identifier-syntax '(())))
799 (define-syntax top-wrap (identifier-syntax '((top))))
801 (define-syntax top-marked?
803 ((_ w) (memq 'top (wrap-marks w)))))
805 ;;; Marks must be comparable with "eq?" and distinct from pairs and
806 ;;; the symbol top. We do not use integers so that marks will remain
807 ;;; unique even across file compiles.
809 (define-syntax the-anti-mark (identifier-syntax #f))
813 (make-wrap (cons the-anti-mark (wrap-marks w))
814 (cons 'shift (wrap-subst w)))))
816 (define-syntax new-mark
820 ;;; make-empty-ribcage and extend-ribcage maintain list-based ribcages for
821 ;;; internal definitions, in which the ribcages are built incrementally
822 (define-syntax make-empty-ribcage
824 ((_) (make-ribcage '() '() '()))))
826 (define extend-ribcage!
827 ; must receive ids with complete wraps
828 (lambda (ribcage id label)
829 (set-ribcage-symnames! ribcage
830 (cons (syntax-object-expression id)
831 (ribcage-symnames ribcage)))
832 (set-ribcage-marks! ribcage
833 (cons (wrap-marks (syntax-object-wrap id))
834 (ribcage-marks ribcage)))
835 (set-ribcage-labels! ribcage
836 (cons label (ribcage-labels ribcage)))))
838 ;;; make-binding-wrap creates vector-based ribcages
839 (define make-binding-wrap
840 (lambda (ids labels w)
846 (let ((labelvec (list->vector labels)))
847 (let ((n (vector-length labelvec)))
848 (let ((symnamevec (make-vector n)) (marksvec (make-vector n)))
849 (let f ((ids ids) (i 0))
850 (if (not (null? ids))
852 (lambda () (id-sym-name&marks (car ids) w))
853 (lambda (symname marks)
854 (vector-set! symnamevec i symname)
855 (vector-set! marksvec i marks)
856 (f (cdr ids) (fx+ i 1))))))
857 (make-ribcage symnamevec marksvec labelvec))))
868 (let ((m1 (wrap-marks w1)) (s1 (wrap-subst w1)))
874 (smart-append s1 (wrap-subst w2))))
876 (smart-append m1 (wrap-marks w2))
877 (smart-append s1 (wrap-subst w2)))))))
881 (smart-append m1 m2)))
888 (eq? (car x) (car y))
889 (same-marks? (cdr x) (cdr y))))))
895 ((_ e) (call-with-values (lambda () e) (lambda (x . ignore) x)))))
897 (lambda (sym subst marks)
900 (let ((fst (car subst)))
902 (search sym (cdr subst) (cdr marks))
903 (let ((symnames (ribcage-symnames fst)))
904 (if (vector? symnames)
905 (search-vector-rib sym subst marks symnames fst)
906 (search-list-rib sym subst marks symnames fst))))))))
907 (define search-list-rib
908 (lambda (sym subst marks symnames ribcage)
909 (let f ((symnames symnames) (i 0))
911 ((null? symnames) (search sym (cdr subst) marks))
912 ((and (eq? (car symnames) sym)
913 (same-marks? marks (list-ref (ribcage-marks ribcage) i)))
914 (values (list-ref (ribcage-labels ribcage) i) marks))
915 (else (f (cdr symnames) (fx+ i 1)))))))
916 (define search-vector-rib
917 (lambda (sym subst marks symnames ribcage)
918 (let ((n (vector-length symnames)))
921 ((fx= i n) (search sym (cdr subst) marks))
922 ((and (eq? (vector-ref symnames i) sym)
923 (same-marks? marks (vector-ref (ribcage-marks ribcage) i)))
924 (values (vector-ref (ribcage-labels ribcage) i) marks))
925 (else (f (fx+ i 1))))))))
928 (or (first (search id (wrap-subst w) (wrap-marks w))) id))
930 (let ((id (syntax-object-expression id))
931 (w1 (syntax-object-wrap id)))
932 (let ((marks (join-marks (wrap-marks w) (wrap-marks w1))))
933 (call-with-values (lambda () (search id (wrap-subst w) marks))
934 (lambda (new-id marks)
936 (first (search id (wrap-subst w1) marks))
938 (else (syntax-violation 'id-var-name "invalid id" id)))))
940 ;;; free-id=? must be passed fully wrapped ids since (free-id=? x y)
941 ;;; may be true even if (free-id=? (wrap x w) (wrap y w)) is not.
945 (and (eq? (id-sym-name i) (id-sym-name j)) ; accelerator
946 (eq? (id-var-name i empty-wrap) (id-var-name j empty-wrap)))))
948 ;;; bound-id=? may be passed unwrapped (or partially wrapped) ids as
949 ;;; long as the missing portion of the wrap is common to both of the ids
950 ;;; since (bound-id=? x y) iff (bound-id=? (wrap x w) (wrap y w))
954 (if (and (syntax-object? i) (syntax-object? j))
955 (and (eq? (syntax-object-expression i)
956 (syntax-object-expression j))
957 (same-marks? (wrap-marks (syntax-object-wrap i))
958 (wrap-marks (syntax-object-wrap j))))
961 ;;; "valid-bound-ids?" returns #t if it receives a list of distinct ids.
962 ;;; valid-bound-ids? may be passed unwrapped (or partially wrapped) ids
963 ;;; as long as the missing portion of the wrap is common to all of the
966 (define valid-bound-ids?
968 (and (let all-ids? ((ids ids))
971 (all-ids? (cdr ids)))))
972 (distinct-bound-ids? ids))))
974 ;;; distinct-bound-ids? expects a list of ids and returns #t if there are
975 ;;; no duplicates. It is quadratic on the length of the id list; long
976 ;;; lists could be sorted to make it more efficient. distinct-bound-ids?
977 ;;; may be passed unwrapped (or partially wrapped) ids as long as the
978 ;;; missing portion of the wrap is common to all of the ids.
980 (define distinct-bound-ids?
982 (let distinct? ((ids ids))
984 (and (not (bound-id-member? (car ids) (cdr ids)))
985 (distinct? (cdr ids)))))))
987 (define bound-id-member?
989 (and (not (null? list))
990 (or (bound-id=? x (car list))
991 (bound-id-member? x (cdr list))))))
993 ;;; wrapping expressions and identifiers
998 ((and (null? (wrap-marks w)) (null? (wrap-subst w))) x)
1001 (syntax-object-expression x)
1002 (join-wraps w (syntax-object-wrap x))
1003 (syntax-object-module x)))
1005 (else (make-syntax-object x w defmod)))))
1008 (lambda (x w s defmod)
1009 (wrap (decorate-source x s) w defmod)))
1013 (define chi-sequence
1014 (lambda (body r w s mod)
1016 (let dobody ((body body) (r r) (w w) (mod mod))
1019 (let ((first (chi (car body) r w mod)))
1020 (cons first (dobody (cdr body) r w mod))))))))
1022 (define chi-top-sequence
1023 (lambda (body r w s m esew mod)
1024 ;; Expanding a sequence of toplevel expressions can affect the
1025 ;; expansion-time environment in several ways -- by adding or changing
1026 ;; top-level syntactic bindings, by defining new modules, and by changing
1027 ;; the current module -- among other ways.
1029 ;; Of all of these, changes to the current module need to be treated
1030 ;; specially, as modules have specific support in the expander, for
1031 ;; purposes of maintaining hygiene. (In contrast, changes to parts of the
1032 ;; global state that are not specifically treated by the expander are
1033 ;; visible by default, without special support.)
1035 ;; So, the deal. In the expression, (begin (define-module (foo)) (bar)),
1036 ;; we need to expand (bar) within the (foo) module. More generally, in a
1037 ;; top-level sequence, if the module after expanding a form is not the
1038 ;; same as the module before expanding the form, we expand subsequent
1039 ;; forms in the new module.
1041 (let dobody ((body body) (r r) (w w) (m m) (esew esew) (mod mod)
1042 (module (current-module)) (out '()))
1045 (let* ((first (chi-top (car body) r w m esew mod))
1046 (new-module (current-module)))
1047 (dobody (cdr body) r w m esew
1048 (if (eq? module new-module)
1050 (cons 'hygiene (module-name new-module)))
1051 new-module (cons first out))))))))
1053 (define chi-install-global
1055 (build-global-definition
1060 (build-primref no-source 'make-syntax-transformer)
1061 (list (build-data no-source name)
1062 (build-data no-source 'macro)
1065 (build-primref no-source 'cons)
1069 (build-primref no-source 'module-name)
1070 (list (build-application
1072 (build-primref no-source 'current-module)
1075 (define chi-when-list
1076 (lambda (e when-list w)
1077 ; when-list is syntax'd version of list of situations
1078 (let f ((when-list when-list) (situations '()))
1079 (if (null? when-list)
1082 (cons (let ((x (car when-list)))
1084 ((free-id=? x #'compile) 'compile)
1085 ((free-id=? x #'load) 'load)
1086 ((free-id=? x #'eval) 'eval)
1087 (else (syntax-violation 'eval-when
1092 ;;; syntax-type returns six values: type, value, e, w, s, and mod. The
1093 ;;; first two are described in the table below.
1095 ;;; type value explanation
1096 ;;; -------------------------------------------------------------------
1097 ;;; core procedure core singleton
1098 ;;; core-form procedure core form
1099 ;;; module-ref procedure @ or @@ singleton
1100 ;;; lexical name lexical variable reference
1101 ;;; global name global variable reference
1102 ;;; begin none begin keyword
1103 ;;; define none define keyword
1104 ;;; define-syntax none define-syntax keyword
1105 ;;; local-syntax rec? letrec-syntax/let-syntax keyword
1106 ;;; eval-when none eval-when keyword
1107 ;;; syntax level pattern variable
1108 ;;; displaced-lexical none displaced lexical identifier
1109 ;;; lexical-call name call to lexical variable
1110 ;;; global-call name call to global variable
1111 ;;; call none any other call
1112 ;;; begin-form none begin expression
1113 ;;; define-form id variable definition
1114 ;;; define-syntax-form id syntax definition
1115 ;;; local-syntax-form rec? syntax definition
1116 ;;; eval-when-form none eval-when form
1117 ;;; constant none self-evaluating datum
1118 ;;; other none anything else
1120 ;;; For define-form and define-syntax-form, e is the rhs expression.
1121 ;;; For all others, e is the entire form. w is the wrap for e.
1122 ;;; s is the source for the entire form. mod is the module for e.
1124 ;;; syntax-type expands macros and unwraps as necessary to get to
1125 ;;; one of the forms above. It also parses define and define-syntax
1126 ;;; forms, although perhaps this should be done by the consumer.
1129 (lambda (e r w s rib mod for-car?)
1132 (let* ((n (id-var-name e w))
1133 (b (lookup n r mod))
1134 (type (binding-type b)))
1136 ((lexical) (values type (binding-value b) e w s mod))
1137 ((global) (values type n e w s mod))
1140 (values type (binding-value b) e w s mod)
1141 (syntax-type (chi-macro (binding-value b) e r w rib mod)
1142 r empty-wrap s rib mod #f)))
1143 (else (values type (binding-value b) e w s mod)))))
1145 (let ((first (car e)))
1147 (lambda () (syntax-type first r w s rib mod #t))
1148 (lambda (ftype fval fe fw fs fmod)
1151 (values 'lexical-call fval e w s mod))
1153 ;; If we got here via an (@@ ...) expansion, we need to
1154 ;; make sure the fmod information is propagated back
1155 ;; correctly -- hence this consing.
1156 (values 'global-call (make-syntax-object fval w fmod)
1159 (syntax-type (chi-macro fval e r w rib mod)
1160 r empty-wrap s rib mod for-car?))
1162 (call-with-values (lambda () (fval e))
1164 (syntax-type sym r w s rib mod for-car?))))
1166 (values 'core-form fval e w s mod))
1168 (values 'local-syntax-form fval e w s mod))
1170 (values 'begin-form #f e w s mod))
1172 (values 'eval-when-form #f e w s mod))
1177 (values 'define-form #'name #'val w s mod))
1178 ((_ (name . args) e1 e2 ...)
1180 (valid-bound-ids? (lambda-var-list #'args)))
1181 ; need lambda here...
1182 (values 'define-form (wrap #'name w mod)
1184 (cons #'lambda (wrap #'(args e1 e2 ...) w mod))
1189 (values 'define-form (wrap #'name w mod)
1191 empty-wrap s mod))))
1196 (values 'define-syntax-form #'name
1199 (values 'call #f e w s mod)))))))
1201 (syntax-type (syntax-object-expression e)
1203 (join-wraps w (syntax-object-wrap e))
1204 s rib (or (syntax-object-module e) mod) for-car?))
1205 ((self-evaluating? e) (values 'constant #f e w s mod))
1206 (else (values 'other #f e w s mod)))))
1209 (lambda (e r w m esew mod)
1210 (define-syntax eval-if-c&e
1214 (if (eq? m 'c&e) (top-level-eval-hook x mod))
1217 (lambda () (syntax-type e r w (source-annotation e) #f mod #f))
1218 (lambda (type value e w s mod)
1224 (chi-top-sequence #'(e1 e2 ...) r w s m esew mod))))
1225 ((local-syntax-form)
1226 (chi-local-syntax value e r w s mod
1227 (lambda (body r w s mod)
1228 (chi-top-sequence body r w s m esew mod))))
1231 ((_ (x ...) e1 e2 ...)
1232 (let ((when-list (chi-when-list e #'(x ...) w))
1233 (body #'(e1 e2 ...)))
1236 (if (memq 'eval when-list)
1237 (chi-top-sequence body r w s 'e '(eval) mod)
1239 ((memq 'load when-list)
1240 (if (or (memq 'compile when-list)
1241 (and (eq? m 'c&e) (memq 'eval when-list)))
1242 (chi-top-sequence body r w s 'c&e '(compile load) mod)
1243 (if (memq m '(c c&e))
1244 (chi-top-sequence body r w s 'c '(load) mod)
1246 ((or (memq 'compile when-list)
1247 (and (eq? m 'c&e) (memq 'eval when-list)))
1248 (top-level-eval-hook
1249 (chi-top-sequence body r w s 'e '(eval) mod)
1252 (else (chi-void)))))))
1253 ((define-syntax-form)
1254 (let ((n (id-var-name value w)) (r (macros-only-env r)))
1257 (if (memq 'compile esew)
1258 (let ((e (chi-install-global n (chi e r w mod))))
1259 (top-level-eval-hook e mod)
1260 (if (memq 'load esew) e (chi-void)))
1261 (if (memq 'load esew)
1262 (chi-install-global n (chi e r w mod))
1265 (let ((e (chi-install-global n (chi e r w mod))))
1266 (top-level-eval-hook e mod)
1269 (if (memq 'eval esew)
1270 (top-level-eval-hook
1271 (chi-install-global n (chi e r w mod))
1275 (let* ((n (id-var-name value w))
1276 (type (binding-type (lookup n r mod))))
1278 ((global core macro module-ref)
1279 ;; affect compile-time environment (once we have booted)
1280 (if (and (memq m '(c c&e))
1281 (not (module-local-variable (current-module) n))
1283 (let ((old (module-variable (current-module) n)))
1284 ;; use value of the same-named imported variable, if
1286 (module-define! (current-module) n
1291 (build-global-definition s n (chi e r w mod))
1293 ((displaced-lexical)
1294 (syntax-violation #f "identifier out of context"
1295 e (wrap value w mod)))
1297 (syntax-violation #f "cannot define keyword at top level"
1298 e (wrap value w mod))))))
1299 (else (eval-if-c&e m (chi-expr type value e r w s mod) mod)))))))
1304 (lambda () (syntax-type e r w (source-annotation e) #f mod #f))
1305 (lambda (type value e w s mod)
1306 (chi-expr type value e r w s mod)))))
1309 (lambda (type value e r w s mod)
1312 (build-lexical-reference 'value s e value))
1314 ;; apply transformer
1315 (value e r w s mod))
1317 (call-with-values (lambda () (value e))
1318 ;; we could add a public? arg here
1319 (lambda (id mod) (build-global-reference s id mod))))
1322 (build-lexical-reference 'fun (source-annotation (car e))
1327 (build-global-reference (source-annotation (car e))
1328 (if (syntax-object? value)
1329 (syntax-object-expression value)
1331 (if (syntax-object? value)
1332 (syntax-object-module value)
1335 ((constant) (build-data s (strip (source-wrap e w s mod) empty-wrap)))
1336 ((global) (build-global-reference s value mod))
1337 ((call) (chi-application (chi (car e) r w mod) e r w s mod))
1340 ((_ e1 e2 ...) (chi-sequence #'(e1 e2 ...) r w s mod))))
1341 ((local-syntax-form)
1342 (chi-local-syntax value e r w s mod chi-sequence))
1345 ((_ (x ...) e1 e2 ...)
1346 (let ((when-list (chi-when-list e #'(x ...) w)))
1347 (if (memq 'eval when-list)
1348 (chi-sequence #'(e1 e2 ...) r w s mod)
1350 ((define-form define-syntax-form)
1351 (syntax-violation #f "definition in expression context"
1352 e (wrap value w mod)))
1354 (syntax-violation #f "reference to pattern variable outside syntax form"
1355 (source-wrap e w s mod)))
1356 ((displaced-lexical)
1357 (syntax-violation #f "reference to identifier outside its scope"
1358 (source-wrap e w s mod)))
1359 (else (syntax-violation #f "unexpected syntax"
1360 (source-wrap e w s mod))))))
1362 (define chi-application
1363 (lambda (x e r w s mod)
1366 (build-application s x
1367 (map (lambda (e) (chi e r w mod)) #'(e1 ...)))))))
1369 ;; (What follows is my interpretation of what's going on here -- Andy)
1371 ;; A macro takes an expression, a tree, the leaves of which are identifiers
1372 ;; and datums. Identifiers are symbols along with a wrap and a module. For
1373 ;; efficiency, subtrees that share wraps and modules may be grouped as one
1376 ;; Going into the expansion, the expression is given an anti-mark, which
1377 ;; logically propagates to all leaves. Then, in the new expression returned
1378 ;; from the transfomer, if we see an expression with an anti-mark, we know it
1379 ;; pertains to the original expression; conversely, expressions without the
1380 ;; anti-mark are known to be introduced by the transformer.
1382 ;; OK, good until now. We know this algorithm does lexical scoping
1383 ;; appropriately because it's widely known in the literature, and psyntax is
1384 ;; widely used. But what about modules? Here we're on our own. What we do is
1385 ;; to mark the module of expressions produced by a macro as pertaining to the
1386 ;; module that was current when the macro was defined -- that is, free
1387 ;; identifiers introduced by a macro are scoped in the macro's module, not in
1388 ;; the expansion's module. Seems to work well.
1390 ;; The only wrinkle is when we want a macro to expand to code in another
1391 ;; module, as is the case for the r6rs `library' form -- the body expressions
1392 ;; should be scoped relative the the new module, the one defined by the macro.
1393 ;; For that, use `(@@ mod-name body)'.
1395 (lambda (p e r w rib mod)
1396 ;; p := (procedure . module-name)
1397 (define rebuild-macro-output
1400 (cons (rebuild-macro-output (car x) m)
1401 (rebuild-macro-output (cdr x) m)))
1403 (let ((w (syntax-object-wrap x)))
1404 (let ((ms (wrap-marks w)) (s (wrap-subst w)))
1405 (if (and (pair? ms) (eq? (car ms) the-anti-mark))
1406 ;; output is from original text
1408 (syntax-object-expression x)
1409 (make-wrap (cdr ms) (if rib (cons rib (cdr s)) (cdr s)))
1410 (syntax-object-module x))
1411 ;; output introduced by macro
1413 (syntax-object-expression x)
1414 (make-wrap (cons m ms)
1416 (cons rib (cons 'shift s))
1418 ;; hither the hygiene
1419 (cons 'hygiene (cdr p)))))))
1422 (let* ((n (vector-length x)) (v (make-vector n)))
1423 (do ((i 0 (fx+ i 1)))
1426 (rebuild-macro-output (vector-ref x i) m)))))
1428 (syntax-violation #f "encountered raw symbol in macro output"
1429 (source-wrap e w (wrap-subst w) mod) x))
1431 (rebuild-macro-output ((car p) (wrap e (anti-mark w) mod)) (new-mark))))
1434 ;; In processing the forms of the body, we create a new, empty wrap.
1435 ;; This wrap is augmented (destructively) each time we discover that
1436 ;; the next form is a definition. This is done:
1438 ;; (1) to allow the first nondefinition form to be a call to
1439 ;; one of the defined ids even if the id previously denoted a
1440 ;; definition keyword or keyword for a macro expanding into a
1442 ;; (2) to prevent subsequent definition forms (but unfortunately
1443 ;; not earlier ones) and the first nondefinition form from
1444 ;; confusing one of the bound identifiers for an auxiliary
1446 ;; (3) so that we do not need to restart the expansion of the
1447 ;; first nondefinition form, which is problematic anyway
1448 ;; since it might be the first element of a begin that we
1449 ;; have just spliced into the body (meaning if we restarted,
1450 ;; we'd really need to restart with the begin or the macro
1451 ;; call that expanded into the begin, and we'd have to give
1452 ;; up allowing (begin <defn>+ <expr>+), which is itself
1453 ;; problematic since we don't know if a begin contains only
1454 ;; definitions until we've expanded it).
1456 ;; Before processing the body, we also create a new environment
1457 ;; containing a placeholder for the bindings we will add later and
1458 ;; associate this environment with each form. In processing a
1459 ;; let-syntax or letrec-syntax, the associated environment may be
1460 ;; augmented with local keyword bindings, so the environment may
1461 ;; be different for different forms in the body. Once we have
1462 ;; gathered up all of the definitions, we evaluate the transformer
1463 ;; expressions and splice into r at the placeholder the new variable
1464 ;; and keyword bindings. This allows let-syntax or letrec-syntax
1465 ;; forms local to a portion or all of the body to shadow the
1466 ;; definition bindings.
1468 ;; Subforms of a begin, let-syntax, or letrec-syntax are spliced
1471 ;; outer-form is fully wrapped w/source
1472 (lambda (body outer-form r w mod)
1473 (let* ((r (cons '("placeholder" . (placeholder)) r))
1474 (ribcage (make-empty-ribcage))
1475 (w (make-wrap (wrap-marks w) (cons ribcage (wrap-subst w)))))
1476 (let parse ((body (map (lambda (x) (cons r (wrap x w mod))) body))
1477 (ids '()) (labels '())
1478 (var-ids '()) (vars '()) (vals '()) (bindings '()))
1480 (syntax-violation #f "no expressions in body" outer-form)
1481 (let ((e (cdar body)) (er (caar body)))
1483 (lambda () (syntax-type e er empty-wrap (source-annotation er) ribcage mod #f))
1484 (lambda (type value e w s mod)
1487 (let ((id (wrap value w mod)) (label (gen-label)))
1488 (let ((var (gen-var id)))
1489 (extend-ribcage! ribcage id label)
1491 (cons id ids) (cons label labels)
1493 (cons var vars) (cons (cons er (wrap e w mod)) vals)
1494 (cons (make-binding 'lexical var) bindings)))))
1495 ((define-syntax-form)
1496 (let ((id (wrap value w mod)) (label (gen-label)))
1497 (extend-ribcage! ribcage id label)
1499 (cons id ids) (cons label labels)
1501 (cons (make-binding 'macro (cons er (wrap e w mod)))
1506 (parse (let f ((forms #'(e1 ...)))
1509 (cons (cons er (wrap (car forms) w mod))
1511 ids labels var-ids vars vals bindings))))
1512 ((local-syntax-form)
1513 (chi-local-syntax value e er w s mod
1514 (lambda (forms er w s mod)
1515 (parse (let f ((forms forms))
1518 (cons (cons er (wrap (car forms) w mod))
1520 ids labels var-ids vars vals bindings))))
1521 (else ; found a non-definition
1523 (build-sequence no-source
1525 (chi (cdr x) (car x) empty-wrap mod))
1526 (cons (cons er (source-wrap e w s mod))
1529 (if (not (valid-bound-ids? ids))
1531 #f "invalid or duplicate identifier in definition"
1533 (let loop ((bs bindings) (er-cache #f) (r-cache #f))
1534 (if (not (null? bs))
1535 (let* ((b (car bs)))
1536 (if (eq? (car b) 'macro)
1537 (let* ((er (cadr b))
1539 (if (eq? er er-cache)
1541 (macros-only-env er))))
1543 (eval-local-transformer
1544 (chi (cddr b) r-cache empty-wrap mod)
1546 (loop (cdr bs) er r-cache))
1547 (loop (cdr bs) er-cache r-cache)))))
1548 (set-cdr! r (extend-env labels bindings (cdr r)))
1549 (build-letrec no-source
1550 (map syntax->datum var-ids)
1553 (chi (cdr x) (car x) empty-wrap mod))
1555 (build-sequence no-source
1557 (chi (cdr x) (car x) empty-wrap mod))
1558 (cons (cons er (source-wrap e w s mod))
1559 (cdr body)))))))))))))))))
1561 (define chi-local-syntax
1562 (lambda (rec? e r w s mod k)
1564 ((_ ((id val) ...) e1 e2 ...)
1565 (let ((ids #'(id ...)))
1566 (if (not (valid-bound-ids? ids))
1567 (syntax-violation #f "duplicate bound keyword" e)
1568 (let ((labels (gen-labels ids)))
1569 (let ((new-w (make-binding-wrap ids labels w)))
1573 (let ((w (if rec? new-w w))
1574 (trans-r (macros-only-env r)))
1576 (make-binding 'macro
1577 (eval-local-transformer
1578 (chi x trans-r w mod)
1585 (_ (syntax-violation #f "bad local syntax definition"
1586 (source-wrap e w s mod))))))
1588 (define eval-local-transformer
1589 (lambda (expanded mod)
1590 (let ((p (local-eval-hook expanded mod)))
1592 (cons p (module-name (current-module)))
1593 (syntax-violation #f "nonprocedure transformer" p)))))
1597 (build-void no-source)))
1601 (and (nonsymbol-id? x)
1602 (free-id=? x #'(... ...)))))
1604 (define lambda-formals
1606 (define (req args rreq)
1607 (syntax-case args ()
1609 (check (reverse rreq) #f))
1611 (req #'b (cons #'a rreq)))
1613 (check (reverse rreq) #'r))
1615 (syntax-violation 'lambda "invalid argument list" orig-args args))))
1616 (define (check req rest)
1618 ((distinct-bound-ids? (if rest (cons rest req) req))
1619 (values req #f rest #f))
1621 (syntax-violation 'lambda "duplicate identifier in argument list"
1623 (req orig-args '())))
1625 (define chi-simple-lambda
1626 (lambda (e r w s mod req rest meta body)
1627 (let* ((ids (if rest (append req (list rest)) req))
1628 (vars (map gen-var ids))
1629 (labels (gen-labels ids)))
1630 (build-simple-lambda
1632 (map syntax->datum req) (and rest (syntax->datum rest)) vars
1634 (chi-body body (source-wrap e w s mod)
1635 (extend-var-env labels vars r)
1636 (make-binding-wrap ids labels w)
1639 (define lambda*-formals
1641 (define (req args rreq)
1642 (syntax-case args ()
1644 (check (reverse rreq) '() #f '()))
1646 (req #'b (cons #'a rreq)))
1647 ((a . b) (eq? (syntax->datum #'a) #:optional)
1648 (opt #'b (reverse rreq) '()))
1649 ((a . b) (eq? (syntax->datum #'a) #:key)
1650 (key #'b (reverse rreq) '() '()))
1651 ((a b) (eq? (syntax->datum #'a) #:rest)
1652 (rest #'b (reverse rreq) '() '()))
1654 (rest #'r (reverse rreq) '() '()))
1656 (syntax-violation 'lambda* "invalid argument list" orig-args args))))
1657 (define (opt args req ropt)
1658 (syntax-case args ()
1660 (check req (reverse ropt) #f '()))
1662 (opt #'b req (cons #'(a #f) ropt)))
1663 (((a init) . b) (id? #'a)
1664 (opt #'b req (cons #'(a init) ropt)))
1665 ((a . b) (eq? (syntax->datum #'a) #:key)
1666 (key #'b req (reverse ropt) '()))
1667 ((a b) (eq? (syntax->datum #'a) #:rest)
1668 (rest #'b req (reverse ropt) '()))
1670 (rest #'r req (reverse ropt) '()))
1672 (syntax-violation 'lambda* "invalid optional argument list"
1674 (define (key args req opt rkey)
1675 (syntax-case args ()
1677 (check req opt #f (cons #f (reverse rkey))))
1679 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1680 (key #'b req opt (cons #'(k a #f) rkey))))
1681 (((a init) . b) (id? #'a)
1682 (with-syntax ((k (symbol->keyword (syntax->datum #'a))))
1683 (key #'b req opt (cons #'(k a init) rkey))))
1684 (((a init k) . b) (and (id? #'a)
1685 (keyword? (syntax->datum #'k)))
1686 (key #'b req opt (cons #'(k a init) rkey)))
1687 ((aok) (eq? (syntax->datum #'aok) #:allow-other-keys)
1688 (check req opt #f (cons #t (reverse rkey))))
1689 ((aok a b) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1690 (eq? (syntax->datum #'a) #:rest))
1691 (rest #'b req opt (cons #t (reverse rkey))))
1692 ((aok . r) (and (eq? (syntax->datum #'aok) #:allow-other-keys)
1694 (rest #'r req opt (cons #t (reverse rkey))))
1695 ((a b) (eq? (syntax->datum #'a) #:rest)
1696 (rest #'b req opt (cons #f (reverse rkey))))
1698 (rest #'r req opt (cons #f (reverse rkey))))
1700 (syntax-violation 'lambda* "invalid keyword argument list"
1702 (define (rest args req opt kw)
1703 (syntax-case args ()
1705 (check req opt #'r kw))
1707 (syntax-violation 'lambda* "invalid rest argument"
1709 (define (check req opt rest kw)
1711 ((distinct-bound-ids?
1712 (append req (map car opt) (if rest (list rest) '())
1713 (if (pair? kw) (map cadr (cdr kw)) '())))
1714 (values req opt rest kw))
1716 (syntax-violation 'lambda* "duplicate identifier in argument list"
1718 (req orig-args '())))
1720 (define chi-lambda-case
1721 (lambda (e r w s mod get-formals clauses)
1722 (define (expand-req req opt rest kw body)
1723 (let ((vars (map gen-var req))
1724 (labels (gen-labels req)))
1725 (let ((r* (extend-var-env labels vars r))
1726 (w* (make-binding-wrap req labels w)))
1727 (expand-opt (map syntax->datum req)
1728 opt rest kw body (reverse vars) r* w* '() '()))))
1729 (define (expand-opt req opt rest kw body vars r* w* out inits)
1732 (syntax-case (car opt) ()
1734 (let* ((v (gen-var #'id))
1735 (l (gen-labels (list v)))
1736 (r** (extend-var-env l (list v) r*))
1737 (w** (make-binding-wrap (list #'id) l w*)))
1738 (expand-opt req (cdr opt) rest kw body (cons v vars)
1739 r** w** (cons (syntax->datum #'id) out)
1740 (cons (chi #'i r* w* mod) inits))))))
1742 (let* ((v (gen-var rest))
1743 (l (gen-labels (list v)))
1744 (r* (extend-var-env l (list v) r*))
1745 (w* (make-binding-wrap (list rest) l w*)))
1746 (expand-kw req (if (pair? out) (reverse out) #f)
1747 (syntax->datum rest)
1748 (if (pair? kw) (cdr kw) kw)
1749 body (cons v vars) r* w*
1750 (if (pair? kw) (car kw) #f)
1753 (expand-kw req (if (pair? out) (reverse out) #f) #f
1754 (if (pair? kw) (cdr kw) kw)
1756 (if (pair? kw) (car kw) #f)
1758 (define (expand-kw req opt rest kw body vars r* w* aok out inits)
1761 (syntax-case (car kw) ()
1763 (let* ((v (gen-var #'id))
1764 (l (gen-labels (list v)))
1765 (r** (extend-var-env l (list v) r*))
1766 (w** (make-binding-wrap (list #'id) l w*)))
1767 (expand-kw req opt rest (cdr kw) body (cons v vars)
1769 (cons (list (syntax->datum #'k)
1770 (syntax->datum #'id)
1773 (cons (chi #'i r* w* mod) inits))))))
1775 (expand-body req opt rest
1776 (if (or aok (pair? out)) (cons aok (reverse out)) #f)
1777 body (reverse vars) r* w* (reverse inits) '()))))
1778 (define (expand-body req opt rest kw body vars r* w* inits meta)
1779 (syntax-case body ()
1780 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
1781 (expand-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1784 . ,(syntax->datum #'docstring))))))
1785 ((#((k . v) ...) e1 e2 ...)
1786 (expand-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
1787 (append meta (syntax->datum #'((k . v) ...)))))
1789 (values meta req opt rest kw inits vars
1790 (chi-body #'(e1 e2 ...) (source-wrap e w s mod)
1793 (syntax-case clauses ()
1794 (() (values '() #f))
1795 (((args e1 e2 ...) (args* e1* e2* ...) ...)
1796 (call-with-values (lambda () (get-formals #'args))
1797 (lambda (req opt rest kw)
1798 (call-with-values (lambda ()
1799 (expand-req req opt rest kw #'(e1 e2 ...)))
1800 (lambda (meta req opt rest kw inits vars body)
1803 (chi-lambda-case e r w s mod get-formals
1804 #'((args* e1* e2* ...) ...)))
1805 (lambda (meta* else*)
1808 (build-lambda-case s req opt rest kw inits vars
1809 body else*))))))))))))
1813 ;;; strips syntax-objects down to top-wrap
1815 ;;; since only the head of a list is annotated by the reader, not each pair
1816 ;;; in the spine, we also check for pairs whose cars are annotated in case
1817 ;;; we've been passed the cdr of an annotated list
1826 (strip (syntax-object-expression x) (syntax-object-wrap x)))
1828 (let ((a (f (car x))) (d (f (cdr x))))
1829 (if (and (eq? a (car x)) (eq? d (cdr x)))
1833 (let ((old (vector->list x)))
1834 (let ((new (map f old)))
1835 (if (and-map* eq? old new) x (list->vector new)))))
1838 ;;; lexical variables
1842 (let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
1843 (build-lexical-var no-source id))))
1845 ;; appears to return a reversed list
1846 (define lambda-var-list
1848 (let lvl ((vars vars) (ls '()) (w empty-wrap))
1850 ((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
1851 ((id? vars) (cons (wrap vars w #f) ls))
1853 ((syntax-object? vars)
1854 (lvl (syntax-object-expression vars)
1856 (join-wraps w (syntax-object-wrap vars))))
1857 ; include anything else to be caught by subsequent error
1859 (else (cons vars ls))))))
1861 ;;; core transformers
1863 (global-extend 'local-syntax 'letrec-syntax #t)
1864 (global-extend 'local-syntax 'let-syntax #f)
1866 (global-extend 'core 'fluid-let-syntax
1867 (lambda (e r w s mod)
1869 ((_ ((var val) ...) e1 e2 ...)
1870 (valid-bound-ids? #'(var ...))
1871 (let ((names (map (lambda (x) (id-var-name x w)) #'(var ...))))
1874 (case (binding-type (lookup n r mod))
1875 ((displaced-lexical)
1876 (syntax-violation 'fluid-let-syntax
1877 "identifier out of context"
1879 (source-wrap id w s mod)))))
1884 (source-wrap e w s mod)
1887 (let ((trans-r (macros-only-env r)))
1889 (make-binding 'macro
1890 (eval-local-transformer (chi x trans-r w mod)
1896 (_ (syntax-violation 'fluid-let-syntax "bad syntax"
1897 (source-wrap e w s mod))))))
1899 (global-extend 'core 'quote
1900 (lambda (e r w s mod)
1902 ((_ e) (build-data s (strip #'e w)))
1903 (_ (syntax-violation 'quote "bad syntax"
1904 (source-wrap e w s mod))))))
1906 (global-extend 'core 'syntax
1909 (lambda (src e r maps ellipsis? mod)
1911 (let ((label (id-var-name e empty-wrap)))
1912 (let ((b (lookup label r mod)))
1913 (if (eq? (binding-type b) 'syntax)
1916 (let ((var.lev (binding-value b)))
1917 (gen-ref src (car var.lev) (cdr var.lev) maps)))
1918 (lambda (var maps) (values `(ref ,var) maps)))
1920 (syntax-violation 'syntax "misplaced ellipsis" src)
1921 (values `(quote ,e) maps)))))
1925 (gen-syntax src #'e r maps (lambda (x) #f) mod))
1927 ; this could be about a dozen lines of code, except that we
1928 ; choose to handle #'(x ... ...) forms
1934 (gen-syntax src #'x r
1935 (cons '() maps) ellipsis? mod))
1937 (if (null? (car maps))
1938 (syntax-violation 'syntax "extra ellipsis"
1940 (values (gen-map x (car maps))
1948 (lambda () (k (cons '() maps)))
1950 (if (null? (car maps))
1951 (syntax-violation 'syntax "extra ellipsis" src)
1952 (values (gen-mappend x (car maps))
1954 (_ (call-with-values
1955 (lambda () (gen-syntax src y r maps ellipsis? mod))
1958 (lambda () (k maps))
1960 (values (gen-append x y) maps)))))))))
1963 (lambda () (gen-syntax src #'x r maps ellipsis? mod))
1966 (lambda () (gen-syntax src #'y r maps ellipsis? mod))
1967 (lambda (y maps) (values (gen-cons x y) maps))))))
1971 (gen-syntax src #'(e1 e2 ...) r maps ellipsis? mod))
1972 (lambda (e maps) (values (gen-vector e) maps))))
1973 (_ (values `(quote ,e) maps))))))
1976 (lambda (src var level maps)
1980 (syntax-violation 'syntax "missing ellipsis" src)
1982 (lambda () (gen-ref src var (fx- level 1) (cdr maps)))
1983 (lambda (outer-var outer-maps)
1984 (let ((b (assq outer-var (car maps))))
1986 (values (cdr b) maps)
1987 (let ((inner-var (gen-var 'tmp)))
1989 (cons (cons (cons outer-var inner-var)
1991 outer-maps)))))))))))
1995 `(apply (primitive append) ,(gen-map e map-env))))
1999 (let ((formals (map cdr map-env))
2000 (actuals (map (lambda (x) `(ref ,(car x))) map-env)))
2003 ; identity map equivalence:
2004 ; (map (lambda (x) x) y) == y
2007 (lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
2009 ; eta map equivalence:
2010 ; (map (lambda (x ...) (f x ...)) y ...) == (map f y ...)
2011 `(map (primitive ,(car e))
2012 ,@(map (let ((r (map cons formals actuals)))
2013 (lambda (x) (cdr (assq (cadr x) r))))
2015 (else `(map (lambda ,formals ,e) ,@actuals))))))
2021 (if (eq? (car x) 'quote)
2022 `(quote (,(cadr x) . ,(cadr y)))
2023 (if (eq? (cadr y) '())
2026 ((list) `(list ,x ,@(cdr y)))
2027 (else `(cons ,x ,y)))))
2031 (if (equal? y '(quote ()))
2038 ((eq? (car x) 'list) `(vector ,@(cdr x)))
2039 ((eq? (car x) 'quote) `(quote #(,@(cadr x))))
2040 (else `(list->vector ,x)))))
2046 ((ref) (build-lexical-reference 'value no-source (cadr x) (cadr x)))
2047 ((primitive) (build-primref no-source (cadr x)))
2048 ((quote) (build-data no-source (cadr x)))
2050 (if (list? (cadr x))
2051 (build-simple-lambda no-source (cadr x) #f (cadr x) '() (regen (caddr x)))
2052 (error "how did we get here" x)))
2053 (else (build-application no-source
2054 (build-primref no-source (car x))
2055 (map regen (cdr x)))))))
2057 (lambda (e r w s mod)
2058 (let ((e (source-wrap e w s mod)))
2062 (lambda () (gen-syntax e #'x r '() ellipsis? mod))
2063 (lambda (e maps) (regen e))))
2064 (_ (syntax-violation 'syntax "bad `syntax' form" e)))))))
2066 (global-extend 'core 'lambda
2067 (lambda (e r w s mod)
2070 (call-with-values (lambda () (lambda-formals #'args))
2071 (lambda (req opt rest kw)
2072 (let lp ((body #'(e1 e2 ...)) (meta '()))
2073 (syntax-case body ()
2074 ((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
2078 . ,(syntax->datum #'docstring))))))
2079 ((#((k . v) ...) e1 e2 ...)
2081 (append meta (syntax->datum #'((k . v) ...)))))
2082 (_ (chi-simple-lambda e r w s mod req rest meta body)))))))
2083 (_ (syntax-violation 'lambda "bad lambda" e)))))
2085 (global-extend 'core 'lambda*
2086 (lambda (e r w s mod)
2091 (chi-lambda-case e r w s mod
2092 lambda*-formals #'((args e1 e2 ...))))
2093 (lambda (meta lcase)
2094 (build-case-lambda s meta lcase))))
2095 (_ (syntax-violation 'lambda "bad lambda*" e)))))
2097 (global-extend 'core 'case-lambda
2098 (lambda (e r w s mod)
2100 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
2103 (chi-lambda-case e r w s mod
2105 #'((args e1 e2 ...) (args* e1* e2* ...) ...)))
2106 (lambda (meta lcase)
2107 (build-case-lambda s meta lcase))))
2108 (_ (syntax-violation 'case-lambda "bad case-lambda" e)))))
2110 (global-extend 'core 'case-lambda*
2111 (lambda (e r w s mod)
2113 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
2116 (chi-lambda-case e r w s mod
2118 #'((args e1 e2 ...) (args* e1* e2* ...) ...)))
2119 (lambda (meta lcase)
2120 (build-case-lambda s meta lcase))))
2121 (_ (syntax-violation 'case-lambda "bad case-lambda*" e)))))
2123 (global-extend 'core 'let
2125 (define (chi-let e r w s mod constructor ids vals exps)
2126 (if (not (valid-bound-ids? ids))
2127 (syntax-violation 'let "duplicate bound variable" e)
2128 (let ((labels (gen-labels ids))
2129 (new-vars (map gen-var ids)))
2130 (let ((nw (make-binding-wrap ids labels w))
2131 (nr (extend-var-env labels new-vars r)))
2133 (map syntax->datum ids)
2135 (map (lambda (x) (chi x r w mod)) vals)
2136 (chi-body exps (source-wrap e nw s mod)
2138 (lambda (e r w s mod)
2140 ((_ ((id val) ...) e1 e2 ...)
2141 (and-map id? #'(id ...))
2142 (chi-let e r w s mod
2147 ((_ f ((id val) ...) e1 e2 ...)
2148 (and (id? #'f) (and-map id? #'(id ...)))
2149 (chi-let e r w s mod
2154 (_ (syntax-violation 'let "bad let" (source-wrap e w s mod)))))))
2157 (global-extend 'core 'letrec
2158 (lambda (e r w s mod)
2160 ((_ ((id val) ...) e1 e2 ...)
2161 (and-map id? #'(id ...))
2162 (let ((ids #'(id ...)))
2163 (if (not (valid-bound-ids? ids))
2164 (syntax-violation 'letrec "duplicate bound variable" e)
2165 (let ((labels (gen-labels ids))
2166 (new-vars (map gen-var ids)))
2167 (let ((w (make-binding-wrap ids labels w))
2168 (r (extend-var-env labels new-vars r)))
2170 (map syntax->datum ids)
2172 (map (lambda (x) (chi x r w mod)) #'(val ...))
2173 (chi-body #'(e1 e2 ...)
2174 (source-wrap e w s mod) r w mod)))))))
2175 (_ (syntax-violation 'letrec "bad letrec" (source-wrap e w s mod))))))
2178 (global-extend 'core 'set!
2179 (lambda (e r w s mod)
2183 (let ((val (chi #'val r w mod))
2184 (n (id-var-name #'id w)))
2185 (let ((b (lookup n r mod)))
2186 (case (binding-type b)
2188 (build-lexical-assignment s
2189 (syntax->datum #'id)
2192 ((global) (build-global-assignment s n val mod))
2193 ((displaced-lexical)
2194 (syntax-violation 'set! "identifier out of context"
2196 (else (syntax-violation 'set! "bad set!"
2197 (source-wrap e w s mod)))))))
2198 ((_ (head tail ...) val)
2200 (lambda () (syntax-type #'head r empty-wrap no-source #f mod #t))
2201 (lambda (type value ee ww ss modmod)
2204 (let ((val (chi #'val r w mod)))
2205 (call-with-values (lambda () (value #'(head tail ...)))
2207 (build-global-assignment s id val mod)))))
2209 (build-application s
2210 (chi #'(setter head) r w mod)
2211 (map (lambda (e) (chi e r w mod))
2212 #'(tail ... val))))))))
2213 (_ (syntax-violation 'set! "bad set!" (source-wrap e w s mod))))))
2215 (global-extend 'module-ref '@
2219 (and (and-map id? #'(mod ...)) (id? #'id))
2220 (values (syntax->datum #'id)
2222 #'(public mod ...)))))))
2224 (global-extend 'module-ref '@@
2228 (and (and-map id? #'(mod ...)) (id? #'id))
2229 (values (syntax->datum #'id)
2231 #'(private mod ...)))))))
2233 (global-extend 'core 'if
2234 (lambda (e r w s mod)
2239 (chi #'test r w mod)
2240 (chi #'then r w mod)
2241 (build-void no-source)))
2245 (chi #'test r w mod)
2246 (chi #'then r w mod)
2247 (chi #'else r w mod))))))
2249 (global-extend 'core 'with-fluids
2250 (lambda (e r w s mod)
2252 ((_ ((fluid val) ...) b b* ...)
2255 (map (lambda (x) (chi x r w mod)) #'(fluid ...))
2256 (map (lambda (x) (chi x r w mod)) #'(val ...))
2257 (chi-body #'(b b* ...)
2258 (source-wrap e w s mod) r w mod))))))
2260 (global-extend 'begin 'begin '())
2262 (global-extend 'define 'define '())
2264 (global-extend 'define-syntax 'define-syntax '())
2266 (global-extend 'eval-when 'eval-when '())
2268 (global-extend 'core 'syntax-case
2270 (define convert-pattern
2271 ; accepts pattern & keys
2272 ; returns $sc-dispatch pattern & ids
2273 (lambda (pattern keys)
2279 (lambda () (cvt* (cdr p*) n ids))
2282 (lambda () (cvt (car p*) n ids))
2284 (values (cons x y) ids))))))))
2288 (if (bound-id-member? p keys)
2289 (values (vector 'free-id p) ids)
2290 (values 'any (cons (cons p n) ids)))
2293 (ellipsis? (syntax dots))
2295 (lambda () (cvt (syntax x) (fx+ n 1) ids))
2297 (values (if (eq? p 'any) 'each-any (vector 'each p))
2300 (ellipsis? (syntax dots))
2302 (lambda () (cvt* (syntax (ys ...)) n ids))
2305 (lambda () (cvt (syntax x) (+ n 1) ids))
2307 (values `#(each+ ,x ,(reverse ys) ()) ids))))))
2310 (lambda () (cvt (syntax y) n ids))
2313 (lambda () (cvt (syntax x) n ids))
2315 (values (cons x y) ids))))))
2316 (() (values '() ids))
2319 (lambda () (cvt (syntax (x ...)) n ids))
2320 (lambda (p ids) (values (vector 'vector p) ids))))
2321 (x (values (vector 'atom (strip p empty-wrap)) ids))))))
2322 (cvt pattern 0 '())))
2324 (define build-dispatch-call
2325 (lambda (pvars exp y r mod)
2326 (let ((ids (map car pvars)) (levels (map cdr pvars)))
2327 (let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
2328 (build-application no-source
2329 (build-primref no-source 'apply)
2330 (list (build-simple-lambda no-source (map syntax->datum ids) #f new-vars '()
2334 (map (lambda (var level)
2335 (make-binding 'syntax `(,var . ,level)))
2339 (make-binding-wrap ids labels empty-wrap)
2344 (lambda (x keys clauses r pat fender exp mod)
2346 (lambda () (convert-pattern pat keys))
2349 ((not (distinct-bound-ids? (map car pvars)))
2350 (syntax-violation 'syntax-case "duplicate pattern variable" pat))
2351 ((not (and-map (lambda (x) (not (ellipsis? (car x)))) pvars))
2352 (syntax-violation 'syntax-case "misplaced ellipsis" pat))
2354 (let ((y (gen-var 'tmp)))
2355 ; fat finger binding and references to temp variable y
2356 (build-application no-source
2357 (build-simple-lambda no-source (list 'tmp) #f (list y) '()
2358 (let ((y (build-lexical-reference 'value no-source
2360 (build-conditional no-source
2361 (syntax-case fender ()
2363 (_ (build-conditional no-source
2365 (build-dispatch-call pvars fender y r mod)
2366 (build-data no-source #f))))
2367 (build-dispatch-call pvars exp y r mod)
2368 (gen-syntax-case x keys clauses r mod))))
2369 (list (if (eq? p 'any)
2370 (build-application no-source
2371 (build-primref no-source 'list)
2373 (build-application no-source
2374 (build-primref no-source '$sc-dispatch)
2375 (list x (build-data no-source p)))))))))))))
2377 (define gen-syntax-case
2378 (lambda (x keys clauses r mod)
2380 (build-application no-source
2381 (build-primref no-source 'syntax-violation)
2382 (list (build-data no-source #f)
2383 (build-data no-source
2384 "source expression failed to match any pattern")
2386 (syntax-case (car clauses) ()
2388 (if (and (id? #'pat)
2389 (and-map (lambda (x) (not (free-id=? #'pat x)))
2390 (cons #'(... ...) keys)))
2391 (let ((labels (list (gen-label)))
2392 (var (gen-var #'pat)))
2393 (build-application no-source
2394 (build-simple-lambda
2395 no-source (list (syntax->datum #'pat)) #f (list var)
2399 (list (make-binding 'syntax `(,var . 0)))
2401 (make-binding-wrap #'(pat)
2405 (gen-clause x keys (cdr clauses) r
2406 #'pat #t #'exp mod)))
2408 (gen-clause x keys (cdr clauses) r
2409 #'pat #'fender #'exp mod))
2410 (_ (syntax-violation 'syntax-case "invalid clause"
2413 (lambda (e r w s mod)
2414 (let ((e (source-wrap e w s mod)))
2416 ((_ val (key ...) m ...)
2417 (if (and-map (lambda (x) (and (id? x) (not (ellipsis? x))))
2419 (let ((x (gen-var 'tmp)))
2420 ; fat finger binding and references to temp variable x
2421 (build-application s
2422 (build-simple-lambda no-source (list 'tmp) #f (list x) '()
2423 (gen-syntax-case (build-lexical-reference 'value no-source
2425 #'(key ...) #'(m ...)
2428 (list (chi #'val r empty-wrap mod))))
2429 (syntax-violation 'syntax-case "invalid literals list" e))))))))
2431 ;;; The portable macroexpand seeds chi-top's mode m with 'e (for
2432 ;;; evaluating) and esew (which stands for "eval syntax expanders
2433 ;;; when") with '(eval). In Chez Scheme, m is set to 'c instead of e
2434 ;;; if we are compiling a file, and esew is set to
2435 ;;; (eval-syntactic-expanders-when), which defaults to the list
2436 ;;; '(compile load eval). This means that, by default, top-level
2437 ;;; syntactic definitions are evaluated immediately after they are
2438 ;;; expanded, and the expanded definitions are also residualized into
2439 ;;; the object file if we are compiling a file.
2442 (if (and (pair? x) (equal? (car x) noexpand))
2444 (let ((m (if (null? rest) 'e (car rest)))
2445 (esew (if (or (null? rest) (null? (cdr rest)))
2448 (with-fluids ((*mode* m))
2449 (chi-top x null-env top-wrap m esew
2450 (cons 'hygiene (module-name (current-module)))))))))
2458 (make-syntax-object datum (syntax-object-wrap id) #f)))
2461 ; accepts any object, since syntax objects may consist partially
2462 ; or entirely of unwrapped, nonsymbolic data
2464 (strip x empty-wrap)))
2466 (set! generate-temporaries
2468 (arg-check list? ls 'generate-temporaries)
2469 (map (lambda (x) (wrap (gensym-hook) top-wrap #f)) ls)))
2471 (set! free-identifier=?
2473 (arg-check nonsymbol-id? x 'free-identifier=?)
2474 (arg-check nonsymbol-id? y 'free-identifier=?)
2477 (set! bound-identifier=?
2479 (arg-check nonsymbol-id? x 'bound-identifier=?)
2480 (arg-check nonsymbol-id? y 'bound-identifier=?)
2483 (set! syntax-violation
2484 (lambda (who message form . subform)
2485 (arg-check (lambda (x) (or (not x) (string? x) (symbol? x)))
2486 who 'syntax-violation)
2487 (arg-check string? message 'syntax-violation)
2488 (scm-error 'syntax-error 'macroexpand
2492 (if (null? subform) "in ~a" "in subform `~s' of `~s'"))
2493 (let ((tail (cons message
2494 (map (lambda (x) (strip x empty-wrap))
2495 (append subform (list form))))))
2496 (if who (cons who tail) tail))
2499 ;;; $sc-dispatch expects an expression and a pattern. If the expression
2500 ;;; matches the pattern a list of the matching expressions for each
2501 ;;; "any" is returned. Otherwise, #f is returned. (This use of #f will
2502 ;;; not work on r4rs implementations that violate the ieee requirement
2503 ;;; that #f and () be distinct.)
2505 ;;; The expression is matched with the pattern as follows:
2507 ;;; pattern: matches:
2510 ;;; (<pattern>1 . <pattern>2) (<pattern>1 . <pattern>2)
2512 ;;; #(free-id <key>) <key> with free-identifier=?
2513 ;;; #(each <pattern>) (<pattern>*)
2514 ;;; #(each+ p1 (p2_1 ... p2_n) p3) (p1* (p2_n ... p2_1) . p3)
2515 ;;; #(vector <pattern>) (list->vector <pattern>)
2516 ;;; #(atom <object>) <object> with "equal?"
2518 ;;; Vector cops out to pair under assumption that vectors are rare. If
2519 ;;; not, should convert to:
2520 ;;; #(vector <pattern>*) #(<pattern>*)
2528 (let ((first (match (car e) p w '() mod)))
2530 (let ((rest (match-each (cdr e) p w mod)))
2531 (and rest (cons first rest))))))
2534 (match-each (syntax-object-expression e)
2536 (join-wraps w (syntax-object-wrap e))
2537 (syntax-object-module e)))
2541 (lambda (e x-pat y-pat z-pat w r mod)
2542 (let f ((e e) (w w))
2545 (call-with-values (lambda () (f (cdr e) w))
2546 (lambda (xr* y-pat r)
2549 (let ((xr (match (car e) x-pat w '() mod)))
2551 (values (cons xr xr*) y-pat r)
2556 (match (car e) (car y-pat) w r mod)))
2557 (values #f #f #f)))))
2559 (f (syntax-object-expression e) (join-wraps w e)))
2561 (values '() y-pat (match e z-pat w r mod)))))))
2563 (define match-each-any
2567 (let ((l (match-each-any (cdr e) w mod)))
2568 (and l (cons (wrap (car e) w mod) l))))
2571 (match-each-any (syntax-object-expression e)
2572 (join-wraps w (syntax-object-wrap e))
2580 ((eq? p 'any) (cons '() r))
2581 ((pair? p) (match-empty (car p) (match-empty (cdr p) r)))
2582 ((eq? p 'each-any) (cons '() r))
2584 (case (vector-ref p 0)
2585 ((each) (match-empty (vector-ref p 1) r))
2586 ((each+) (match-empty (vector-ref p 1)
2588 (reverse (vector-ref p 2))
2589 (match-empty (vector-ref p 3) r))))
2591 ((vector) (match-empty (vector-ref p 1) r)))))))
2595 (if (null? (car r*))
2597 (cons (map car r*) (combine (map cdr r*) r)))))
2600 (lambda (e p w r mod)
2602 ((null? p) (and (null? e) r))
2604 (and (pair? e) (match (car e) (car p) w
2605 (match (cdr e) (cdr p) w r mod)
2608 (let ((l (match-each-any e w mod))) (and l (cons l r))))
2610 (case (vector-ref p 0)
2613 (match-empty (vector-ref p 1) r)
2614 (let ((l (match-each e (vector-ref p 1) w mod)))
2616 (let collect ((l l))
2619 (cons (map car l) (collect (map cdr l)))))))))
2623 (match-each+ e (vector-ref p 1) (vector-ref p 2) (vector-ref p 3) w r mod))
2624 (lambda (xr* y-pat r)
2628 (match-empty (vector-ref p 1) r)
2629 (combine xr* r))))))
2630 ((free-id) (and (id? e) (free-id=? (wrap e w mod) (vector-ref p 1)) r))
2631 ((atom) (and (equal? (vector-ref p 1) (strip e w)) r))
2634 (match (vector->list e) (vector-ref p 1) w r mod))))))))
2637 (lambda (e p w r mod)
2640 ((eq? p 'any) (cons (wrap e w mod) r))
2643 (syntax-object-expression e)
2645 (join-wraps w (syntax-object-wrap e))
2647 (syntax-object-module e)))
2648 (else (match* e p w r mod)))))
2653 ((eq? p 'any) (list e))
2655 (match* (syntax-object-expression e)
2656 p (syntax-object-wrap e) '() (syntax-object-module e)))
2657 (else (match* e p empty-wrap '() #f)))))
2662 (define-syntax with-syntax
2666 #'(begin e1 e2 ...))
2667 ((_ ((out in)) e1 e2 ...)
2668 #'(syntax-case in () (out (begin e1 e2 ...))))
2669 ((_ ((out in) ...) e1 e2 ...)
2670 #'(syntax-case (list in ...) ()
2671 ((out ...) (begin e1 e2 ...)))))))
2673 (define-syntax syntax-rules
2676 ((_ (k ...) ((keyword . pattern) template) ...)
2678 ;; embed patterns as procedure metadata
2679 #((macro-type . syntax-rules)
2680 (patterns pattern ...))
2681 (syntax-case x (k ...)
2682 ((dummy . pattern) #'template)
2688 ((let* ((x v) ...) e1 e2 ...)
2689 (and-map identifier? #'(x ...))
2690 (let f ((bindings #'((x v) ...)))
2691 (if (null? bindings)
2692 #'(let () e1 e2 ...)
2693 (with-syntax ((body (f (cdr bindings)))
2694 (binding (car bindings)))
2695 #'(let (binding) body))))))))
2699 (syntax-case orig-x ()
2700 ((_ ((var init . step) ...) (e0 e1 ...) c ...)
2701 (with-syntax (((step ...)
2706 (_ (syntax-violation
2707 'do "bad step expression"
2711 (syntax-case #'(e1 ...) ()
2712 (() #'(let doloop ((var init) ...)
2714 (begin c ... (doloop step ...)))))
2716 #'(let doloop ((var init) ...)
2719 (begin c ... (doloop step ...)))))))))))
2721 (define-syntax quasiquote
2725 (with-syntax ((x x) (y y))
2726 (syntax-case #'y (quote list)
2728 (syntax-case #'x (quote)
2729 ((quote dx) #'(quote (dx . dy)))
2733 ((list . stuff) #'(list x . stuff))
2734 (else #'(cons x y))))))
2737 (with-syntax ((x x) (y y))
2738 (syntax-case #'y (quote)
2740 (_ #'(append x y))))))
2743 (with-syntax ((x x))
2744 (syntax-case #'x (quote list)
2745 ((quote (x ...)) #'(quote #(x ...)))
2746 ((list x ...) #'(vector x ...))
2747 (_ #'(list->vector x))))))
2750 (syntax-case p (unquote unquote-splicing quasiquote)
2754 (quasicons #'(quote unquote)
2755 (quasi #'(p) (- lev 1)))))
2758 (syntax-violation 'unquote
2759 "unquote takes exactly one argument"
2760 p #'(unquote . args)))
2761 (((unquote-splicing p) . q)
2763 (quasiappend #'p (quasi #'q lev))
2764 (quasicons (quasicons #'(quote unquote-splicing)
2765 (quasi #'(p) (- lev 1)))
2767 (((unquote-splicing . args) . q)
2769 (syntax-violation 'unquote-splicing
2770 "unquote-splicing takes exactly one argument"
2771 p #'(unquote-splicing . args)))
2773 (quasicons #'(quote quasiquote)
2774 (quasi #'(p) (+ lev 1))))
2776 (quasicons (quasi #'p lev) (quasi #'q lev)))
2777 (#(x ...) (quasivector (quasi #'(x ...) lev)))
2781 ((_ e) (quasi #'e 0))))))
2783 (define-syntax include
2787 (let ((p (open-input-file fn)))
2788 (let f ((x (read p))
2792 (close-input-port p)
2795 (cons (datum->syntax k x) result)))))))
2798 (let ((fn (syntax->datum #'filename)))
2799 (with-syntax (((exp ...) (read-file fn #'k)))
2800 #'(begin exp ...)))))))
2802 (define-syntax include-from-path
2806 (let ((fn (syntax->datum #'filename)))
2807 (with-syntax ((fn (or (%search-load-path fn)
2808 (syntax-violation 'include-from-path
2809 "file not found in path"
2811 #'(include fn)))))))
2813 (define-syntax unquote
2817 (syntax-violation 'unquote
2818 "expression not valid outside of quasiquote"
2821 (define-syntax unquote-splicing
2825 (syntax-violation 'unquote-splicing
2826 "expression not valid outside of quasiquote"
2834 ((body (let f ((clause #'m1) (clauses #'(m2 ...)))
2836 (syntax-case clause (else)
2837 ((else e1 e2 ...) #'(begin e1 e2 ...))
2838 (((k ...) e1 e2 ...)
2839 #'(if (memv t '(k ...)) (begin e1 e2 ...)))
2840 (_ (syntax-violation 'case "bad clause" x clause)))
2841 (with-syntax ((rest (f (car clauses) (cdr clauses))))
2842 (syntax-case clause (else)
2843 (((k ...) e1 e2 ...)
2844 #'(if (memv t '(k ...))
2847 (_ (syntax-violation 'case "bad clause" x
2849 #'(let ((t e)) body))))))
2851 (define-syntax identifier-syntax
2856 #((macro-type . identifier-syntax))
2862 #'(e x (... ...)))))))))
2864 (define-syntax define*
2867 ((_ (id . args) b0 b1 ...)
2868 #'(define id (lambda* args b0 b1 ...)))
2869 ((_ id val) (identifier? #'x)
2870 #'(define id val)))))