add explanatory comment to chi-macro
[bpt/guile.git] / module / ice-9 / psyntax.scm
1 ;;;; -*-scheme-*-
2 ;;;;
3 ;;;; Copyright (C) 2001, 2003, 2006, 2009, 2010 Free Software Foundation, Inc.
4 ;;;;
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 ;;;;
19 \f
20
21 ;;; Portable implementation of syntax-case
22 ;;; Extracted from Chez Scheme Version 5.9f
23 ;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
24
25 ;;; Modified by Andy Wingo <wingo@pobox.com> according to the Git
26 ;;; revision control logs corresponding to this file: 2009.
27
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
32
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.
43
44 ;;; Before attempting to port this code to a new implementation of
45 ;;; Scheme, please read the notes below carefully.
46
47
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.
53 ;;;
54 ;;; bound-identifier=?
55 ;;; datum->syntax
56 ;;; define-syntax
57 ;;; fluid-let-syntax
58 ;;; free-identifier=?
59 ;;; generate-temporaries
60 ;;; identifier?
61 ;;; identifier-syntax
62 ;;; let-syntax
63 ;;; letrec-syntax
64 ;;; syntax
65 ;;; syntax-case
66 ;;; syntax->datum
67 ;;; syntax-rules
68 ;;; with-syntax
69 ;;;
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.
73
74 ;;; The remaining exports are listed below:
75 ;;;
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
89
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.
94 ;;;
95 ;;; (eval x)
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.
100 ;;;
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.
107 ;;;
108 ;;; (gensym)
109 ;;; returns a unique symbol each time it's called
110
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.
119
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.
125
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.
131
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?
137 ;;; (syntax-rules ()
138 ;;; ((_ w) (memq 'top (wrap-marks w)))))
139 ;;; rather than
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.
153
154
155 ;;; implementation information:
156
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.
160
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.
167
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.
172
173 ;;; All identifiers that don't have macro definitions and are not bound
174 ;;; lexically are assumed to be global variables
175
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.
180
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.
186
187 ;;; Identifiers and syntax objects are implemented as vectors for
188 ;;; portability. As a result, it is possible to "forge" syntax
189 ;;; objects.
190
191 ;;; The implementation of generate-temporaries assumes that it is possible
192 ;;; to generate globally unique symbols (gensyms).
193
194
195 ;;; Bootstrapping:
196
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.
201
202
203
204 (eval-when (compile)
205 (set-current-module (resolve-module '(guile))))
206
207 (let ()
208 ;;; Private version of and-map that handles multiple lists.
209 (define and-map*
210 (lambda (f first . rest)
211 (or (null? first)
212 (if (null? rest)
213 (let andmap ((first first))
214 (let ((x (car first)) (first (cdr first)))
215 (if (null? first)
216 (f x)
217 (and (f x) (andmap first)))))
218 (let andmap ((first first) (rest rest))
219 (let ((x (car first))
220 (xr (map car rest))
221 (first (cdr first))
222 (rest (map cdr rest)))
223 (if (null? first)
224 (apply f (cons x xr))
225 (and (apply f (cons x xr)) (andmap first rest)))))))))
226
227 (define-syntax define-structure
228 (lambda (x)
229 (define construct-name
230 (lambda (template-identifier . args)
231 (datum->syntax
232 template-identifier
233 (string->symbol
234 (apply string-append
235 (map (lambda (x)
236 (if (string? x)
237 x
238 (symbol->string (syntax->datum x))))
239 args))))))
240 (syntax-case x ()
241 ((_ (name id1 ...))
242 (and-map identifier? #'(name id1 ...))
243 (with-syntax
244 ((constructor (construct-name #'name "make-" #'name))
245 (predicate (construct-name #'name #'name "?"))
246 ((access ...)
247 (map (lambda (x) (construct-name x #'name "-" x))
248 #'(id1 ...)))
249 ((assign ...)
250 (map (lambda (x)
251 (construct-name x "set-" #'name "-" x "!"))
252 #'(id1 ...)))
253 (structure-length
254 (+ (length #'(id1 ...)) 1))
255 ((index ...)
256 (let f ((i 1) (ids #'(id1 ...)))
257 (if (null? ids)
258 '()
259 (cons i (f (+ i 1) (cdr ids)))))))
260 #'(begin
261 (define constructor
262 (lambda (id1 ...)
263 (vector 'name id1 ... )))
264 (define predicate
265 (lambda (x)
266 (and (vector? x)
267 (= (vector-length x) structure-length)
268 (eq? (vector-ref x 0) 'name))))
269 (define access
270 (lambda (x)
271 (vector-ref x index)))
272 ...
273 (define assign
274 (lambda (x update)
275 (vector-set! x index update)))
276 ...))))))
277
278 (let ()
279 (define noexpand "noexpand")
280 (define *mode* (make-fluid))
281
282 ;;; hooks to nonportable run-time helpers
283 (begin
284 (define fx+ +)
285 (define fx- -)
286 (define fx= =)
287 (define fx< <)
288
289 (define top-level-eval-hook
290 (lambda (x mod)
291 (primitive-eval
292 `(,noexpand
293 ,(case (fluid-ref *mode*)
294 ((c) ((@ (language tree-il) tree-il->scheme) x))
295 (else x))))))
296
297 (define local-eval-hook
298 (lambda (x mod)
299 (primitive-eval
300 `(,noexpand
301 ,(case (fluid-ref *mode*)
302 ((c) ((@ (language tree-il) tree-il->scheme) x))
303 (else x))))))
304
305 (define-syntax gensym-hook
306 (syntax-rules ()
307 ((_) (gensym))))
308
309 (define put-global-definition-hook
310 (lambda (symbol type val)
311 (module-define! (current-module)
312 symbol
313 (make-syntax-transformer symbol type val))))
314
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))
321 (current-module))
322 symbol)))
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))))))))
328
329 )
330
331
332 (define (decorate-source e s)
333 (if (and (pair? e) s)
334 (set-source-properties! e s))
335 e)
336
337 ;;; output constructors
338 (define build-void
339 (lambda (source)
340 (case (fluid-ref *mode*)
341 ((c) ((@ (language tree-il) make-void) source))
342 (else (decorate-source '(if #f #f) source)))))
343
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)))))
349
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))
359 source)))))
360
361 (define build-dynlet
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)
366 source)))))
367
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)))))
373
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)))))
379
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
386 ;; holds true.
387 ;;
388 (define (analyze-variable mod var modref-cont bare-cont)
389 (if (not mod)
390 (bare-cont var)
391 (let ((kind (car mod))
392 (mod (cdr mod)))
393 (case kind
394 ((public) (modref-cont mod var #t))
395 ((private) (if (not (equal? mod (module-name (current-module))))
396 (modref-cont mod var #f)
397 (bare-cont var)))
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)
402 (bare-cont var)))
403 (else (syntax-violation #f "bad module kind" var mod))))))
404
405 (define build-global-reference
406 (lambda (source var mod)
407 (analyze-variable
408 mod var
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))))
413 (lambda (var)
414 (case (fluid-ref *mode*)
415 ((c) ((@ (language tree-il) make-toplevel-ref) source var))
416 (else (decorate-source var source)))))))
417
418 (define build-global-assignment
419 (lambda (source var exp mod)
420 (analyze-variable
421 mod var
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))))
426 (lambda (var)
427 (case (fluid-ref *mode*)
428 ((c) ((@ (language tree-il) make-toplevel-set) source var exp))
429 (else (decorate-source `(set! ,var ,exp) source)))))))
430
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)
434 (cond
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))
439 val
440 (acons 'name name meta)))))))
441
442 (define build-global-definition
443 (lambda (source var exp)
444 (case (fluid-ref *mode*)
445 ((c)
446 (maybe-name-value! var exp)
447 ((@ (language tree-il) make-toplevel-define) source var exp))
448 (else (decorate-source `(define ,var ,exp) source)))))
449
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
454 ;; the cases.
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
459 meta
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)
466 ,exp)
467 src)))))
468 (define build-case-lambda
469 (lambda (src meta body)
470 (case (fluid-ref *mode*)
471 ((c) ((@ (language tree-il) make-lambda) src
472 meta
473 body))
474 (else (decorate-source
475 ;; really gross hack
476 `(lambda %%args
477 (cond ,@body))
478 src)))))
479
480 (define build-lambda-case
481 ;; req := (name ...)
482 ;; opt := (name ...) | #f
483 ;; rest := name | #f
484 ;; kw := (allow-other-keys? (keyword name var [init]) ...) | #f
485 ;; inits: (init ...)
486 ;; vars: (sym ...)
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*)
493 ((c)
494 ((@ (language tree-il) make-lambda-case)
495 src req opt rest kw inits vars body else-case))
496 (else
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)
503 ;; (,key ,name ,var)
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)))))
508 (or (= nargs
509 (length vars)
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))
513 (decorate-source
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))
517 %%args)
518 => (lambda (%%args) (apply (lambda ,vars ,body) %%args)))
519 ,@(or else-case
520 `((%%args (scm-error 'wrong-number-of-args #f
521 "Wrong number of arguments" '()
522 %%args)))))
523 src))))))
524
525 (define build-primref
526 (lambda (src name)
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))))))
534
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)))
540 exp
541 (list 'quote exp))
542 src))))
543
544 (define build-sequence
545 (lambda (src exps)
546 (if (null? (cdr exps))
547 (car exps)
548 (case (fluid-ref *mode*)
549 ((c) ((@ (language tree-il) make-sequence) src exps))
550 (else (decorate-source `(begin ,@exps) src))))))
551
552 (define build-let
553 (lambda (src ids vars val-exps body-exp)
554 (if (null? vars)
555 body-exp
556 (case (fluid-ref *mode*)
557 ((c)
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)
562 src))))))
563
564 (define build-named-let
565 (lambda (src ids vars val-exps body-exp)
566 (let ((f (car vars))
567 (f-name (car ids))
568 (vars (cdr vars))
569 (ids (cdr ids)))
570 (case (fluid-ref *mode*)
571 ((c)
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)
578 val-exps))))
579 (else (decorate-source
580 `(letrec ((,f (lambda ,vars ,body-exp)))
581 (,f ,@val-exps))
582 src))))))
583
584 (define build-letrec
585 (lambda (src ids vars val-exps body-exp)
586 (if (null? vars)
587 body-exp
588 (case (fluid-ref *mode*)
589 ((c)
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)
594 src))))))
595
596 ;; FIXME: use a faster gensym
597 (define-syntax build-lexical-var
598 (syntax-rules ()
599 ((_ src id) (gensym (string-append (symbol->string id) " ")))))
600
601 (define-structure (syntax-object expression wrap module))
602
603 (define-syntax no-source (identifier-syntax #f))
604
605 (define source-annotation
606 (lambda (x)
607 (cond
608 ((syntax-object? x)
609 (source-annotation (syntax-object-expression x)))
610 ((pair? x) (let ((props (source-properties x)))
611 (if (pair? props)
612 props
613 #f)))
614 (else #f))))
615
616 (define-syntax arg-check
617 (syntax-rules ()
618 ((_ pred? e who)
619 (let ((x e))
620 (if (not (pred? x)) (syntax-violation who "invalid argument" x))))))
621
622 ;;; compile-time environments
623
624 ;;; wrap and environment comprise two level mapping.
625 ;;; wrap : id --> label
626 ;;; env : label --> <element>
627
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
632 ;;; bindings.
633
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.
637
638 ;;; <environment> ::= ((<label> . <binding>)*)
639
640 ;;; identifier bindings include a type and a value
641
642 ;;; <binding> ::= (macro . <procedure>) macros
643 ;;; (core . <procedure>) core forms
644 ;;; (module-ref . <procedure>) @ or @@
645 ;;; (begin) begin
646 ;;; (define) define
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
656
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
661 ;;; definitions.
662
663 ;;; a pattern variable is a variable introduced by syntax-case and can
664 ;;; be referenced only within a syntax form.
665
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
668 ;;; variable.
669
670 ;;; a lexical variable is a lambda- or letrec-bound variable.
671
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.
677
678 (define-syntax make-binding
679 (syntax-rules (quote)
680 ((_ type value) (cons type value))
681 ((_ 'type) '(type))
682 ((_ type) (cons type '()))))
683 (define binding-type car)
684 (define binding-value cdr)
685
686 (define-syntax null-env (identifier-syntax '()))
687
688 (define extend-env
689 (lambda (labels bindings r)
690 (if (null? labels)
691 r
692 (extend-env (cdr labels) (cdr bindings)
693 (cons (cons (car labels) (car bindings)) r)))))
694
695 (define extend-var-env
696 ; variant of extend-env that forms "lexical" binding
697 (lambda (labels vars r)
698 (if (null? labels)
699 r
700 (extend-var-env (cdr labels) (cdr vars)
701 (cons (cons (car labels) (make-binding 'lexical (car vars))) r)))))
702
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
707 (lambda (r)
708 (if (null? r)
709 '()
710 (let ((a (car r)))
711 (if (eq? (cadr a) 'macro)
712 (cons a (macros-only-env (cdr r)))
713 (macros-only-env (cdr r)))))))
714
715 (define lookup
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
719 ; fluid-let-syntax
720 (lambda (x r mod)
721 (cond
722 ((assq x r) => cdr)
723 ((symbol? x)
724 (or (get-global-definition-hook x mod) (make-binding 'global)))
725 (else (make-binding 'displaced-lexical)))))
726
727 (define global-extend
728 (lambda (type sym val)
729 (put-global-definition-hook sym type val)))
730
731
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.
736
737 (define nonsymbol-id?
738 (lambda (x)
739 (and (syntax-object? x)
740 (symbol? (syntax-object-expression x)))))
741
742 (define id?
743 (lambda (x)
744 (cond
745 ((symbol? x) #t)
746 ((syntax-object? x) (symbol? (syntax-object-expression x)))
747 (else #f))))
748
749 (define-syntax id-sym-name
750 (syntax-rules ()
751 ((_ e)
752 (let ((x e))
753 (if (syntax-object? x)
754 (syntax-object-expression x)
755 x)))))
756
757 (define id-sym-name&marks
758 (lambda (x w)
759 (if (syntax-object? x)
760 (values
761 (syntax-object-expression x)
762 (join-marks (wrap-marks w) (wrap-marks (syntax-object-wrap x))))
763 (values x (wrap-marks w)))))
764
765 ;;; syntax object wraps
766
767 ;;; <wrap> ::= ((<mark> ...) . (<subst> ...))
768 ;;; <subst> ::= <shift> | <subs>
769 ;;; <subs> ::= #(<old name> <label> (<mark> ...))
770 ;;; <shift> ::= positive fixnum
771
772 (define make-wrap cons)
773 (define wrap-marks car)
774 (define wrap-subst cdr)
775
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
781 (syntax-rules ()
782 ((_ old new marks) (vector old new marks))))
783
784 ;;; labels must be comparable with "eq?", have read-write invariance,
785 ;;; and distinct from symbols.
786 (define gen-label
787 (lambda () (symbol->string (gensym "i"))))
788
789 (define gen-labels
790 (lambda (ls)
791 (if (null? ls)
792 '()
793 (cons (gen-label) (gen-labels (cdr ls))))))
794
795 (define-structure (ribcage symnames marks labels))
796
797 (define-syntax empty-wrap (identifier-syntax '(())))
798
799 (define-syntax top-wrap (identifier-syntax '((top))))
800
801 (define-syntax top-marked?
802 (syntax-rules ()
803 ((_ w) (memq 'top (wrap-marks w)))))
804
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.
808
809 (define-syntax the-anti-mark (identifier-syntax #f))
810
811 (define anti-mark
812 (lambda (w)
813 (make-wrap (cons the-anti-mark (wrap-marks w))
814 (cons 'shift (wrap-subst w)))))
815
816 (define-syntax new-mark
817 (syntax-rules ()
818 ((_) (gensym "m"))))
819
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
823 (syntax-rules ()
824 ((_) (make-ribcage '() '() '()))))
825
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)))))
837
838 ;;; make-binding-wrap creates vector-based ribcages
839 (define make-binding-wrap
840 (lambda (ids labels w)
841 (if (null? ids)
842 w
843 (make-wrap
844 (wrap-marks w)
845 (cons
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))
851 (call-with-values
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))))
858 (wrap-subst w))))))
859
860 (define smart-append
861 (lambda (m1 m2)
862 (if (null? m2)
863 m1
864 (append m1 m2))))
865
866 (define join-wraps
867 (lambda (w1 w2)
868 (let ((m1 (wrap-marks w1)) (s1 (wrap-subst w1)))
869 (if (null? m1)
870 (if (null? s1)
871 w2
872 (make-wrap
873 (wrap-marks w2)
874 (smart-append s1 (wrap-subst w2))))
875 (make-wrap
876 (smart-append m1 (wrap-marks w2))
877 (smart-append s1 (wrap-subst w2)))))))
878
879 (define join-marks
880 (lambda (m1 m2)
881 (smart-append m1 m2)))
882
883 (define same-marks?
884 (lambda (x y)
885 (or (eq? x y)
886 (and (not (null? x))
887 (not (null? y))
888 (eq? (car x) (car y))
889 (same-marks? (cdr x) (cdr y))))))
890
891 (define id-var-name
892 (lambda (id w)
893 (define-syntax first
894 (syntax-rules ()
895 ((_ e) (call-with-values (lambda () e) (lambda (x . ignore) x)))))
896 (define search
897 (lambda (sym subst marks)
898 (if (null? subst)
899 (values #f marks)
900 (let ((fst (car subst)))
901 (if (eq? fst 'shift)
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))
910 (cond
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)))
919 (let f ((i 0))
920 (cond
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))))))))
926 (cond
927 ((symbol? id)
928 (or (first (search id (wrap-subst w) (wrap-marks w))) id))
929 ((syntax-object? 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)
935 (or new-id
936 (first (search id (wrap-subst w1) marks))
937 id))))))
938 (else (syntax-violation 'id-var-name "invalid id" id)))))
939
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.
942
943 (define free-id=?
944 (lambda (i j)
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)))))
947
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))
951
952 (define bound-id=?
953 (lambda (i j)
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))))
959 (eq? i j))))
960
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
964 ;;; ids.
965
966 (define valid-bound-ids?
967 (lambda (ids)
968 (and (let all-ids? ((ids ids))
969 (or (null? ids)
970 (and (id? (car ids))
971 (all-ids? (cdr ids)))))
972 (distinct-bound-ids? ids))))
973
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.
979
980 (define distinct-bound-ids?
981 (lambda (ids)
982 (let distinct? ((ids ids))
983 (or (null? ids)
984 (and (not (bound-id-member? (car ids) (cdr ids)))
985 (distinct? (cdr ids)))))))
986
987 (define bound-id-member?
988 (lambda (x list)
989 (and (not (null? list))
990 (or (bound-id=? x (car list))
991 (bound-id-member? x (cdr list))))))
992
993 ;;; wrapping expressions and identifiers
994
995 (define wrap
996 (lambda (x w defmod)
997 (cond
998 ((and (null? (wrap-marks w)) (null? (wrap-subst w))) x)
999 ((syntax-object? x)
1000 (make-syntax-object
1001 (syntax-object-expression x)
1002 (join-wraps w (syntax-object-wrap x))
1003 (syntax-object-module x)))
1004 ((null? x) x)
1005 (else (make-syntax-object x w defmod)))))
1006
1007 (define source-wrap
1008 (lambda (x w s defmod)
1009 (wrap (decorate-source x s) w defmod)))
1010
1011 ;;; expanding
1012
1013 (define chi-sequence
1014 (lambda (body r w s mod)
1015 (build-sequence s
1016 (let dobody ((body body) (r r) (w w) (mod mod))
1017 (if (null? body)
1018 '()
1019 (let ((first (chi (car body) r w mod)))
1020 (cons first (dobody (cdr body) r w mod))))))))
1021
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.
1028 ;;
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.)
1034 ;;
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.
1040 (build-sequence s
1041 (let dobody ((body body) (r r) (w w) (m m) (esew esew) (mod mod)
1042 (module (current-module)) (out '()))
1043 (if (null? body)
1044 (reverse 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)
1049 mod
1050 (cons 'hygiene (module-name new-module)))
1051 new-module (cons first out))))))))
1052
1053 (define chi-install-global
1054 (lambda (name e)
1055 (build-global-definition
1056 no-source
1057 name
1058 (build-application
1059 no-source
1060 (build-primref no-source 'make-syntax-transformer)
1061 (list (build-data no-source name)
1062 (build-data no-source 'macro)
1063 (build-application
1064 no-source
1065 (build-primref no-source 'cons)
1066 (list e
1067 (build-application
1068 no-source
1069 (build-primref no-source 'module-name)
1070 (list (build-application
1071 no-source
1072 (build-primref no-source 'current-module)
1073 '()))))))))))
1074
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)
1080 situations
1081 (f (cdr when-list)
1082 (cons (let ((x (car when-list)))
1083 (cond
1084 ((free-id=? x #'compile) 'compile)
1085 ((free-id=? x #'load) 'load)
1086 ((free-id=? x #'eval) 'eval)
1087 (else (syntax-violation 'eval-when
1088 "invalid situation"
1089 e (wrap x w #f)))))
1090 situations))))))
1091
1092 ;;; syntax-type returns six values: type, value, e, w, s, and mod. The
1093 ;;; first two are described in the table below.
1094 ;;;
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
1119 ;;;
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.
1123 ;;;
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.
1127
1128 (define syntax-type
1129 (lambda (e r w s rib mod for-car?)
1130 (cond
1131 ((symbol? e)
1132 (let* ((n (id-var-name e w))
1133 (b (lookup n r mod))
1134 (type (binding-type b)))
1135 (case type
1136 ((lexical) (values type (binding-value b) e w s mod))
1137 ((global) (values type n e w s mod))
1138 ((macro)
1139 (if for-car?
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)))))
1144 ((pair? e)
1145 (let ((first (car e)))
1146 (call-with-values
1147 (lambda () (syntax-type first r w s rib mod #t))
1148 (lambda (ftype fval fe fw fs fmod)
1149 (case ftype
1150 ((lexical)
1151 (values 'lexical-call fval e w s mod))
1152 ((global)
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)
1157 e w s mod))
1158 ((macro)
1159 (syntax-type (chi-macro fval e r w rib mod)
1160 r empty-wrap s rib mod for-car?))
1161 ((module-ref)
1162 (call-with-values (lambda () (fval e))
1163 (lambda (sym mod)
1164 (syntax-type sym r w s rib mod for-car?))))
1165 ((core)
1166 (values 'core-form fval e w s mod))
1167 ((local-syntax)
1168 (values 'local-syntax-form fval e w s mod))
1169 ((begin)
1170 (values 'begin-form #f e w s mod))
1171 ((eval-when)
1172 (values 'eval-when-form #f e w s mod))
1173 ((define)
1174 (syntax-case e ()
1175 ((_ name val)
1176 (id? #'name)
1177 (values 'define-form #'name #'val w s mod))
1178 ((_ (name . args) e1 e2 ...)
1179 (and (id? #'name)
1180 (valid-bound-ids? (lambda-var-list #'args)))
1181 ; need lambda here...
1182 (values 'define-form (wrap #'name w mod)
1183 (decorate-source
1184 (cons #'lambda (wrap #'(args e1 e2 ...) w mod))
1185 s)
1186 empty-wrap s mod))
1187 ((_ name)
1188 (id? #'name)
1189 (values 'define-form (wrap #'name w mod)
1190 #'(if #f #f)
1191 empty-wrap s mod))))
1192 ((define-syntax)
1193 (syntax-case e ()
1194 ((_ name val)
1195 (id? #'name)
1196 (values 'define-syntax-form #'name
1197 #'val w s mod))))
1198 (else
1199 (values 'call #f e w s mod)))))))
1200 ((syntax-object? e)
1201 (syntax-type (syntax-object-expression e)
1202 r
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)))))
1207
1208 (define chi-top
1209 (lambda (e r w m esew mod)
1210 (define-syntax eval-if-c&e
1211 (syntax-rules ()
1212 ((_ m e mod)
1213 (let ((x e))
1214 (if (eq? m 'c&e) (top-level-eval-hook x mod))
1215 x))))
1216 (call-with-values
1217 (lambda () (syntax-type e r w (source-annotation e) #f mod #f))
1218 (lambda (type value e w s mod)
1219 (case type
1220 ((begin-form)
1221 (syntax-case e ()
1222 ((_) (chi-void))
1223 ((_ e1 e2 ...)
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))))
1229 ((eval-when-form)
1230 (syntax-case e ()
1231 ((_ (x ...) e1 e2 ...)
1232 (let ((when-list (chi-when-list e #'(x ...) w))
1233 (body #'(e1 e2 ...)))
1234 (cond
1235 ((eq? m 'e)
1236 (if (memq 'eval when-list)
1237 (chi-top-sequence body r w s 'e '(eval) mod)
1238 (chi-void)))
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)
1245 (chi-void))))
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)
1250 mod)
1251 (chi-void))
1252 (else (chi-void)))))))
1253 ((define-syntax-form)
1254 (let ((n (id-var-name value w)) (r (macros-only-env r)))
1255 (case m
1256 ((c)
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))
1263 (chi-void))))
1264 ((c&e)
1265 (let ((e (chi-install-global n (chi e r w mod))))
1266 (top-level-eval-hook e mod)
1267 e))
1268 (else
1269 (if (memq 'eval esew)
1270 (top-level-eval-hook
1271 (chi-install-global n (chi e r w mod))
1272 mod))
1273 (chi-void)))))
1274 ((define-form)
1275 (let* ((n (id-var-name value w))
1276 (type (binding-type (lookup n r mod))))
1277 (case type
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))
1282 (current-module))
1283 (let ((old (module-variable (current-module) n)))
1284 ;; use value of the same-named imported variable, if
1285 ;; any
1286 (module-define! (current-module) n
1287 (if (variable? old)
1288 (variable-ref old)
1289 #f))))
1290 (eval-if-c&e m
1291 (build-global-definition s n (chi e r w mod))
1292 mod))
1293 ((displaced-lexical)
1294 (syntax-violation #f "identifier out of context"
1295 e (wrap value w mod)))
1296 (else
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)))))))
1300
1301 (define chi
1302 (lambda (e r w mod)
1303 (call-with-values
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)))))
1307
1308 (define chi-expr
1309 (lambda (type value e r w s mod)
1310 (case type
1311 ((lexical)
1312 (build-lexical-reference 'value s e value))
1313 ((core core-form)
1314 ;; apply transformer
1315 (value e r w s mod))
1316 ((module-ref)
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))))
1320 ((lexical-call)
1321 (chi-application
1322 (build-lexical-reference 'fun (source-annotation (car e))
1323 (car e) value)
1324 e r w s mod))
1325 ((global-call)
1326 (chi-application
1327 (build-global-reference (source-annotation (car e))
1328 (if (syntax-object? value)
1329 (syntax-object-expression value)
1330 value)
1331 (if (syntax-object? value)
1332 (syntax-object-module value)
1333 mod))
1334 e r w s mod))
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))
1338 ((begin-form)
1339 (syntax-case e ()
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))
1343 ((eval-when-form)
1344 (syntax-case e ()
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)
1349 (chi-void))))))
1350 ((define-form define-syntax-form)
1351 (syntax-violation #f "definition in expression context"
1352 e (wrap value w mod)))
1353 ((syntax)
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))))))
1361
1362 (define chi-application
1363 (lambda (x e r w s mod)
1364 (syntax-case e ()
1365 ((e0 e1 ...)
1366 (build-application s x
1367 (map (lambda (e) (chi e r w mod)) #'(e1 ...)))))))
1368
1369 ;; (What follows is my interpretation of what's going on here -- Andy)
1370 ;;
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
1374 ;; syntax object.
1375 ;;
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.
1381 ;;
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.
1389 ;;
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)'.
1394 (define chi-macro
1395 (lambda (p e r w rib mod)
1396 ;; p := (procedure . module-name)
1397 (define rebuild-macro-output
1398 (lambda (x m)
1399 (cond ((pair? x)
1400 (cons (rebuild-macro-output (car x) m)
1401 (rebuild-macro-output (cdr x) m)))
1402 ((syntax-object? x)
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
1407 (make-syntax-object
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
1412 (make-syntax-object
1413 (syntax-object-expression x)
1414 (make-wrap (cons m ms)
1415 (if rib
1416 (cons rib (cons 'shift s))
1417 (cons 'shift s)))
1418 ;; hither the hygiene
1419 (cons 'hygiene (cdr p)))))))
1420
1421 ((vector? x)
1422 (let* ((n (vector-length x)) (v (make-vector n)))
1423 (do ((i 0 (fx+ i 1)))
1424 ((fx= i n) v)
1425 (vector-set! v i
1426 (rebuild-macro-output (vector-ref x i) m)))))
1427 ((symbol? x)
1428 (syntax-violation #f "encountered raw symbol in macro output"
1429 (source-wrap e w (wrap-subst w) mod) x))
1430 (else x))))
1431 (rebuild-macro-output ((car p) (wrap e (anti-mark w) mod)) (new-mark))))
1432
1433 (define chi-body
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:
1437 ;;
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
1441 ;; definition;
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
1445 ;; keyword; and
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).
1455 ;;
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.
1467 ;;
1468 ;; Subforms of a begin, let-syntax, or letrec-syntax are spliced
1469 ;; into the body.
1470 ;;
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 '()))
1479 (if (null? body)
1480 (syntax-violation #f "no expressions in body" outer-form)
1481 (let ((e (cdar body)) (er (caar body)))
1482 (call-with-values
1483 (lambda () (syntax-type e er empty-wrap (source-annotation er) ribcage mod #f))
1484 (lambda (type value e w s mod)
1485 (case type
1486 ((define-form)
1487 (let ((id (wrap value w mod)) (label (gen-label)))
1488 (let ((var (gen-var id)))
1489 (extend-ribcage! ribcage id label)
1490 (parse (cdr body)
1491 (cons id ids) (cons label labels)
1492 (cons id var-ids)
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)
1498 (parse (cdr body)
1499 (cons id ids) (cons label labels)
1500 var-ids vars vals
1501 (cons (make-binding 'macro (cons er (wrap e w mod)))
1502 bindings))))
1503 ((begin-form)
1504 (syntax-case e ()
1505 ((_ e1 ...)
1506 (parse (let f ((forms #'(e1 ...)))
1507 (if (null? forms)
1508 (cdr body)
1509 (cons (cons er (wrap (car forms) w mod))
1510 (f (cdr forms)))))
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))
1516 (if (null? forms)
1517 (cdr body)
1518 (cons (cons er (wrap (car forms) w mod))
1519 (f (cdr forms)))))
1520 ids labels var-ids vars vals bindings))))
1521 (else ; found a non-definition
1522 (if (null? ids)
1523 (build-sequence no-source
1524 (map (lambda (x)
1525 (chi (cdr x) (car x) empty-wrap mod))
1526 (cons (cons er (source-wrap e w s mod))
1527 (cdr body))))
1528 (begin
1529 (if (not (valid-bound-ids? ids))
1530 (syntax-violation
1531 #f "invalid or duplicate identifier in definition"
1532 outer-form))
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))
1538 (r-cache
1539 (if (eq? er er-cache)
1540 r-cache
1541 (macros-only-env er))))
1542 (set-cdr! b
1543 (eval-local-transformer
1544 (chi (cddr b) r-cache empty-wrap mod)
1545 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)
1551 vars
1552 (map (lambda (x)
1553 (chi (cdr x) (car x) empty-wrap mod))
1554 vals)
1555 (build-sequence no-source
1556 (map (lambda (x)
1557 (chi (cdr x) (car x) empty-wrap mod))
1558 (cons (cons er (source-wrap e w s mod))
1559 (cdr body)))))))))))))))))
1560
1561 (define chi-local-syntax
1562 (lambda (rec? e r w s mod k)
1563 (syntax-case e ()
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)))
1570 (k #'(e1 e2 ...)
1571 (extend-env
1572 labels
1573 (let ((w (if rec? new-w w))
1574 (trans-r (macros-only-env r)))
1575 (map (lambda (x)
1576 (make-binding 'macro
1577 (eval-local-transformer
1578 (chi x trans-r w mod)
1579 mod)))
1580 #'(val ...)))
1581 r)
1582 new-w
1583 s
1584 mod))))))
1585 (_ (syntax-violation #f "bad local syntax definition"
1586 (source-wrap e w s mod))))))
1587
1588 (define eval-local-transformer
1589 (lambda (expanded mod)
1590 (let ((p (local-eval-hook expanded mod)))
1591 (if (procedure? p)
1592 (cons p (module-name (current-module)))
1593 (syntax-violation #f "nonprocedure transformer" p)))))
1594
1595 (define chi-void
1596 (lambda ()
1597 (build-void no-source)))
1598
1599 (define ellipsis?
1600 (lambda (x)
1601 (and (nonsymbol-id? x)
1602 (free-id=? x #'(... ...)))))
1603
1604 (define lambda-formals
1605 (lambda (orig-args)
1606 (define (req args rreq)
1607 (syntax-case args ()
1608 (()
1609 (check (reverse rreq) #f))
1610 ((a . b) (id? #'a)
1611 (req #'b (cons #'a rreq)))
1612 (r (id? #'r)
1613 (check (reverse rreq) #'r))
1614 (else
1615 (syntax-violation 'lambda "invalid argument list" orig-args args))))
1616 (define (check req rest)
1617 (cond
1618 ((distinct-bound-ids? (if rest (cons rest req) req))
1619 (values req #f rest #f))
1620 (else
1621 (syntax-violation 'lambda "duplicate identifier in argument list"
1622 orig-args))))
1623 (req orig-args '())))
1624
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
1631 s
1632 (map syntax->datum req) (and rest (syntax->datum rest)) vars
1633 meta
1634 (chi-body body (source-wrap e w s mod)
1635 (extend-var-env labels vars r)
1636 (make-binding-wrap ids labels w)
1637 mod)))))
1638
1639 (define lambda*-formals
1640 (lambda (orig-args)
1641 (define (req args rreq)
1642 (syntax-case args ()
1643 (()
1644 (check (reverse rreq) '() #f '()))
1645 ((a . b) (id? #'a)
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) '() '()))
1653 (r (id? #'r)
1654 (rest #'r (reverse rreq) '() '()))
1655 (else
1656 (syntax-violation 'lambda* "invalid argument list" orig-args args))))
1657 (define (opt args req ropt)
1658 (syntax-case args ()
1659 (()
1660 (check req (reverse ropt) #f '()))
1661 ((a . b) (id? #'a)
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) '()))
1669 (r (id? #'r)
1670 (rest #'r req (reverse ropt) '()))
1671 (else
1672 (syntax-violation 'lambda* "invalid optional argument list"
1673 orig-args args))))
1674 (define (key args req opt rkey)
1675 (syntax-case args ()
1676 (()
1677 (check req opt #f (cons #f (reverse rkey))))
1678 ((a . b) (id? #'a)
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)
1693 (id? #'r))
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))))
1697 (r (id? #'r)
1698 (rest #'r req opt (cons #f (reverse rkey))))
1699 (else
1700 (syntax-violation 'lambda* "invalid keyword argument list"
1701 orig-args args))))
1702 (define (rest args req opt kw)
1703 (syntax-case args ()
1704 (r (id? #'r)
1705 (check req opt #'r kw))
1706 (else
1707 (syntax-violation 'lambda* "invalid rest argument"
1708 orig-args args))))
1709 (define (check req opt rest kw)
1710 (cond
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))
1715 (else
1716 (syntax-violation 'lambda* "duplicate identifier in argument list"
1717 orig-args))))
1718 (req orig-args '())))
1719
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)
1730 (cond
1731 ((pair? opt)
1732 (syntax-case (car opt) ()
1733 ((id i)
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))))))
1741 (rest
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)
1751 '() inits)))
1752 (else
1753 (expand-kw req (if (pair? out) (reverse out) #f) #f
1754 (if (pair? kw) (cdr kw) kw)
1755 body vars r* w*
1756 (if (pair? kw) (car kw) #f)
1757 '() inits))))
1758 (define (expand-kw req opt rest kw body vars r* w* aok out inits)
1759 (cond
1760 ((pair? kw)
1761 (syntax-case (car kw) ()
1762 ((k id i)
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)
1768 r** w** aok
1769 (cons (list (syntax->datum #'k)
1770 (syntax->datum #'id)
1771 v)
1772 out)
1773 (cons (chi #'i r* w* mod) inits))))))
1774 (else
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
1782 (append meta
1783 `((documentation
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) ...)))))
1788 ((e1 e2 ...)
1789 (values meta req opt rest kw inits vars
1790 (chi-body #'(e1 e2 ...) (source-wrap e w s mod)
1791 r* w* mod)))))
1792
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)
1801 (call-with-values
1802 (lambda ()
1803 (chi-lambda-case e r w s mod get-formals
1804 #'((args* e1* e2* ...) ...)))
1805 (lambda (meta* else*)
1806 (values
1807 (append meta meta*)
1808 (build-lambda-case s req opt rest kw inits vars
1809 body else*))))))))))))
1810
1811 ;;; data
1812
1813 ;;; strips syntax-objects down to top-wrap
1814 ;;;
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
1818
1819 (define strip
1820 (lambda (x w)
1821 (if (top-marked? w)
1822 x
1823 (let f ((x x))
1824 (cond
1825 ((syntax-object? x)
1826 (strip (syntax-object-expression x) (syntax-object-wrap x)))
1827 ((pair? x)
1828 (let ((a (f (car x))) (d (f (cdr x))))
1829 (if (and (eq? a (car x)) (eq? d (cdr x)))
1830 x
1831 (cons a d))))
1832 ((vector? x)
1833 (let ((old (vector->list x)))
1834 (let ((new (map f old)))
1835 (if (and-map* eq? old new) x (list->vector new)))))
1836 (else x))))))
1837
1838 ;;; lexical variables
1839
1840 (define gen-var
1841 (lambda (id)
1842 (let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
1843 (build-lexical-var no-source id))))
1844
1845 ;; appears to return a reversed list
1846 (define lambda-var-list
1847 (lambda (vars)
1848 (let lvl ((vars vars) (ls '()) (w empty-wrap))
1849 (cond
1850 ((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
1851 ((id? vars) (cons (wrap vars w #f) ls))
1852 ((null? vars) ls)
1853 ((syntax-object? vars)
1854 (lvl (syntax-object-expression vars)
1855 ls
1856 (join-wraps w (syntax-object-wrap vars))))
1857 ; include anything else to be caught by subsequent error
1858 ; checking
1859 (else (cons vars ls))))))
1860
1861 ;;; core transformers
1862
1863 (global-extend 'local-syntax 'letrec-syntax #t)
1864 (global-extend 'local-syntax 'let-syntax #f)
1865
1866 (global-extend 'core 'fluid-let-syntax
1867 (lambda (e r w s mod)
1868 (syntax-case e ()
1869 ((_ ((var val) ...) e1 e2 ...)
1870 (valid-bound-ids? #'(var ...))
1871 (let ((names (map (lambda (x) (id-var-name x w)) #'(var ...))))
1872 (for-each
1873 (lambda (id n)
1874 (case (binding-type (lookup n r mod))
1875 ((displaced-lexical)
1876 (syntax-violation 'fluid-let-syntax
1877 "identifier out of context"
1878 e
1879 (source-wrap id w s mod)))))
1880 #'(var ...)
1881 names)
1882 (chi-body
1883 #'(e1 e2 ...)
1884 (source-wrap e w s mod)
1885 (extend-env
1886 names
1887 (let ((trans-r (macros-only-env r)))
1888 (map (lambda (x)
1889 (make-binding 'macro
1890 (eval-local-transformer (chi x trans-r w mod)
1891 mod)))
1892 #'(val ...)))
1893 r)
1894 w
1895 mod)))
1896 (_ (syntax-violation 'fluid-let-syntax "bad syntax"
1897 (source-wrap e w s mod))))))
1898
1899 (global-extend 'core 'quote
1900 (lambda (e r w s mod)
1901 (syntax-case e ()
1902 ((_ e) (build-data s (strip #'e w)))
1903 (_ (syntax-violation 'quote "bad syntax"
1904 (source-wrap e w s mod))))))
1905
1906 (global-extend 'core 'syntax
1907 (let ()
1908 (define gen-syntax
1909 (lambda (src e r maps ellipsis? mod)
1910 (if (id? e)
1911 (let ((label (id-var-name e empty-wrap)))
1912 (let ((b (lookup label r mod)))
1913 (if (eq? (binding-type b) 'syntax)
1914 (call-with-values
1915 (lambda ()
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)))
1919 (if (ellipsis? e)
1920 (syntax-violation 'syntax "misplaced ellipsis" src)
1921 (values `(quote ,e) maps)))))
1922 (syntax-case e ()
1923 ((dots e)
1924 (ellipsis? #'dots)
1925 (gen-syntax src #'e r maps (lambda (x) #f) mod))
1926 ((x dots . y)
1927 ; this could be about a dozen lines of code, except that we
1928 ; choose to handle #'(x ... ...) forms
1929 (ellipsis? #'dots)
1930 (let f ((y #'y)
1931 (k (lambda (maps)
1932 (call-with-values
1933 (lambda ()
1934 (gen-syntax src #'x r
1935 (cons '() maps) ellipsis? mod))
1936 (lambda (x maps)
1937 (if (null? (car maps))
1938 (syntax-violation 'syntax "extra ellipsis"
1939 src)
1940 (values (gen-map x (car maps))
1941 (cdr maps))))))))
1942 (syntax-case y ()
1943 ((dots . y)
1944 (ellipsis? #'dots)
1945 (f #'y
1946 (lambda (maps)
1947 (call-with-values
1948 (lambda () (k (cons '() maps)))
1949 (lambda (x maps)
1950 (if (null? (car maps))
1951 (syntax-violation 'syntax "extra ellipsis" src)
1952 (values (gen-mappend x (car maps))
1953 (cdr maps))))))))
1954 (_ (call-with-values
1955 (lambda () (gen-syntax src y r maps ellipsis? mod))
1956 (lambda (y maps)
1957 (call-with-values
1958 (lambda () (k maps))
1959 (lambda (x maps)
1960 (values (gen-append x y) maps)))))))))
1961 ((x . y)
1962 (call-with-values
1963 (lambda () (gen-syntax src #'x r maps ellipsis? mod))
1964 (lambda (x maps)
1965 (call-with-values
1966 (lambda () (gen-syntax src #'y r maps ellipsis? mod))
1967 (lambda (y maps) (values (gen-cons x y) maps))))))
1968 (#(e1 e2 ...)
1969 (call-with-values
1970 (lambda ()
1971 (gen-syntax src #'(e1 e2 ...) r maps ellipsis? mod))
1972 (lambda (e maps) (values (gen-vector e) maps))))
1973 (_ (values `(quote ,e) maps))))))
1974
1975 (define gen-ref
1976 (lambda (src var level maps)
1977 (if (fx= level 0)
1978 (values var maps)
1979 (if (null? maps)
1980 (syntax-violation 'syntax "missing ellipsis" src)
1981 (call-with-values
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))))
1985 (if b
1986 (values (cdr b) maps)
1987 (let ((inner-var (gen-var 'tmp)))
1988 (values inner-var
1989 (cons (cons (cons outer-var inner-var)
1990 (car maps))
1991 outer-maps)))))))))))
1992
1993 (define gen-mappend
1994 (lambda (e map-env)
1995 `(apply (primitive append) ,(gen-map e map-env))))
1996
1997 (define gen-map
1998 (lambda (e map-env)
1999 (let ((formals (map cdr map-env))
2000 (actuals (map (lambda (x) `(ref ,(car x))) map-env)))
2001 (cond
2002 ((eq? (car e) 'ref)
2003 ; identity map equivalence:
2004 ; (map (lambda (x) x) y) == y
2005 (car actuals))
2006 ((and-map
2007 (lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
2008 (cdr e))
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))))
2014 (cdr e))))
2015 (else `(map (lambda ,formals ,e) ,@actuals))))))
2016
2017 (define gen-cons
2018 (lambda (x y)
2019 (case (car y)
2020 ((quote)
2021 (if (eq? (car x) 'quote)
2022 `(quote (,(cadr x) . ,(cadr y)))
2023 (if (eq? (cadr y) '())
2024 `(list ,x)
2025 `(cons ,x ,y))))
2026 ((list) `(list ,x ,@(cdr y)))
2027 (else `(cons ,x ,y)))))
2028
2029 (define gen-append
2030 (lambda (x y)
2031 (if (equal? y '(quote ()))
2032 x
2033 `(append ,x ,y))))
2034
2035 (define gen-vector
2036 (lambda (x)
2037 (cond
2038 ((eq? (car x) 'list) `(vector ,@(cdr x)))
2039 ((eq? (car x) 'quote) `(quote #(,@(cadr x))))
2040 (else `(list->vector ,x)))))
2041
2042
2043 (define regen
2044 (lambda (x)
2045 (case (car 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)))
2049 ((lambda)
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)))))))
2056
2057 (lambda (e r w s mod)
2058 (let ((e (source-wrap e w s mod)))
2059 (syntax-case e ()
2060 ((_ x)
2061 (call-with-values
2062 (lambda () (gen-syntax e #'x r '() ellipsis? mod))
2063 (lambda (e maps) (regen e))))
2064 (_ (syntax-violation 'syntax "bad `syntax' form" e)))))))
2065
2066 (global-extend 'core 'lambda
2067 (lambda (e r w s mod)
2068 (syntax-case e ()
2069 ((_ args e1 e2 ...)
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))
2075 (lp #'(e1 e2 ...)
2076 (append meta
2077 `((documentation
2078 . ,(syntax->datum #'docstring))))))
2079 ((#((k . v) ...) e1 e2 ...)
2080 (lp #'(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)))))
2084
2085 (global-extend 'core 'lambda*
2086 (lambda (e r w s mod)
2087 (syntax-case e ()
2088 ((_ args e1 e2 ...)
2089 (call-with-values
2090 (lambda ()
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)))))
2096
2097 (global-extend 'core 'case-lambda
2098 (lambda (e r w s mod)
2099 (syntax-case e ()
2100 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
2101 (call-with-values
2102 (lambda ()
2103 (chi-lambda-case e r w s mod
2104 lambda-formals
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)))))
2109
2110 (global-extend 'core 'case-lambda*
2111 (lambda (e r w s mod)
2112 (syntax-case e ()
2113 ((_ (args e1 e2 ...) (args* e1* e2* ...) ...)
2114 (call-with-values
2115 (lambda ()
2116 (chi-lambda-case e r w s mod
2117 lambda*-formals
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)))))
2122
2123 (global-extend 'core 'let
2124 (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)))
2132 (constructor s
2133 (map syntax->datum ids)
2134 new-vars
2135 (map (lambda (x) (chi x r w mod)) vals)
2136 (chi-body exps (source-wrap e nw s mod)
2137 nr nw mod))))))
2138 (lambda (e r w s mod)
2139 (syntax-case e ()
2140 ((_ ((id val) ...) e1 e2 ...)
2141 (and-map id? #'(id ...))
2142 (chi-let e r w s mod
2143 build-let
2144 #'(id ...)
2145 #'(val ...)
2146 #'(e1 e2 ...)))
2147 ((_ f ((id val) ...) e1 e2 ...)
2148 (and (id? #'f) (and-map id? #'(id ...)))
2149 (chi-let e r w s mod
2150 build-named-let
2151 #'(f id ...)
2152 #'(val ...)
2153 #'(e1 e2 ...)))
2154 (_ (syntax-violation 'let "bad let" (source-wrap e w s mod)))))))
2155
2156
2157 (global-extend 'core 'letrec
2158 (lambda (e r w s mod)
2159 (syntax-case e ()
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)))
2169 (build-letrec s
2170 (map syntax->datum ids)
2171 new-vars
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))))))
2176
2177
2178 (global-extend 'core 'set!
2179 (lambda (e r w s mod)
2180 (syntax-case e ()
2181 ((_ id val)
2182 (id? #'id)
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)
2187 ((lexical)
2188 (build-lexical-assignment s
2189 (syntax->datum #'id)
2190 (binding-value b)
2191 val))
2192 ((global) (build-global-assignment s n val mod))
2193 ((displaced-lexical)
2194 (syntax-violation 'set! "identifier out of context"
2195 (wrap #'id w mod)))
2196 (else (syntax-violation 'set! "bad set!"
2197 (source-wrap e w s mod)))))))
2198 ((_ (head tail ...) val)
2199 (call-with-values
2200 (lambda () (syntax-type #'head r empty-wrap no-source #f mod #t))
2201 (lambda (type value ee ww ss modmod)
2202 (case type
2203 ((module-ref)
2204 (let ((val (chi #'val r w mod)))
2205 (call-with-values (lambda () (value #'(head tail ...)))
2206 (lambda (id mod)
2207 (build-global-assignment s id val mod)))))
2208 (else
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))))))
2214
2215 (global-extend 'module-ref '@
2216 (lambda (e)
2217 (syntax-case e ()
2218 ((_ (mod ...) id)
2219 (and (and-map id? #'(mod ...)) (id? #'id))
2220 (values (syntax->datum #'id)
2221 (syntax->datum
2222 #'(public mod ...)))))))
2223
2224 (global-extend 'module-ref '@@
2225 (lambda (e)
2226 (syntax-case e ()
2227 ((_ (mod ...) id)
2228 (and (and-map id? #'(mod ...)) (id? #'id))
2229 (values (syntax->datum #'id)
2230 (syntax->datum
2231 #'(private mod ...)))))))
2232
2233 (global-extend 'core 'if
2234 (lambda (e r w s mod)
2235 (syntax-case e ()
2236 ((_ test then)
2237 (build-conditional
2238 s
2239 (chi #'test r w mod)
2240 (chi #'then r w mod)
2241 (build-void no-source)))
2242 ((_ test then else)
2243 (build-conditional
2244 s
2245 (chi #'test r w mod)
2246 (chi #'then r w mod)
2247 (chi #'else r w mod))))))
2248
2249 (global-extend 'core 'with-fluids
2250 (lambda (e r w s mod)
2251 (syntax-case e ()
2252 ((_ ((fluid val) ...) b b* ...)
2253 (build-dynlet
2254 s
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))))))
2259
2260 (global-extend 'begin 'begin '())
2261
2262 (global-extend 'define 'define '())
2263
2264 (global-extend 'define-syntax 'define-syntax '())
2265
2266 (global-extend 'eval-when 'eval-when '())
2267
2268 (global-extend 'core 'syntax-case
2269 (let ()
2270 (define convert-pattern
2271 ; accepts pattern & keys
2272 ; returns $sc-dispatch pattern & ids
2273 (lambda (pattern keys)
2274 (define cvt*
2275 (lambda (p* n ids)
2276 (if (null? p*)
2277 (values '() ids)
2278 (call-with-values
2279 (lambda () (cvt* (cdr p*) n ids))
2280 (lambda (y ids)
2281 (call-with-values
2282 (lambda () (cvt (car p*) n ids))
2283 (lambda (x ids)
2284 (values (cons x y) ids))))))))
2285 (define cvt
2286 (lambda (p n ids)
2287 (if (id? p)
2288 (if (bound-id-member? p keys)
2289 (values (vector 'free-id p) ids)
2290 (values 'any (cons (cons p n) ids)))
2291 (syntax-case p ()
2292 ((x dots)
2293 (ellipsis? (syntax dots))
2294 (call-with-values
2295 (lambda () (cvt (syntax x) (fx+ n 1) ids))
2296 (lambda (p ids)
2297 (values (if (eq? p 'any) 'each-any (vector 'each p))
2298 ids))))
2299 ((x dots ys ...)
2300 (ellipsis? (syntax dots))
2301 (call-with-values
2302 (lambda () (cvt* (syntax (ys ...)) n ids))
2303 (lambda (ys ids)
2304 (call-with-values
2305 (lambda () (cvt (syntax x) (+ n 1) ids))
2306 (lambda (x ids)
2307 (values `#(each+ ,x ,(reverse ys) ()) ids))))))
2308 ((x . y)
2309 (call-with-values
2310 (lambda () (cvt (syntax y) n ids))
2311 (lambda (y ids)
2312 (call-with-values
2313 (lambda () (cvt (syntax x) n ids))
2314 (lambda (x ids)
2315 (values (cons x y) ids))))))
2316 (() (values '() ids))
2317 (#(x ...)
2318 (call-with-values
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 '())))
2323
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 '()
2331 (chi exp
2332 (extend-env
2333 labels
2334 (map (lambda (var level)
2335 (make-binding 'syntax `(,var . ,level)))
2336 new-vars
2337 (map cdr pvars))
2338 r)
2339 (make-binding-wrap ids labels empty-wrap)
2340 mod))
2341 y))))))
2342
2343 (define gen-clause
2344 (lambda (x keys clauses r pat fender exp mod)
2345 (call-with-values
2346 (lambda () (convert-pattern pat keys))
2347 (lambda (p pvars)
2348 (cond
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))
2353 (else
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
2359 'tmp y)))
2360 (build-conditional no-source
2361 (syntax-case fender ()
2362 (#t y)
2363 (_ (build-conditional no-source
2364 y
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)
2372 (list x))
2373 (build-application no-source
2374 (build-primref no-source '$sc-dispatch)
2375 (list x (build-data no-source p)))))))))))))
2376
2377 (define gen-syntax-case
2378 (lambda (x keys clauses r mod)
2379 (if (null? clauses)
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")
2385 x))
2386 (syntax-case (car clauses) ()
2387 ((pat exp)
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)
2396 '()
2397 (chi #'exp
2398 (extend-env labels
2399 (list (make-binding 'syntax `(,var . 0)))
2400 r)
2401 (make-binding-wrap #'(pat)
2402 labels empty-wrap)
2403 mod))
2404 (list x)))
2405 (gen-clause x keys (cdr clauses) r
2406 #'pat #t #'exp mod)))
2407 ((pat fender exp)
2408 (gen-clause x keys (cdr clauses) r
2409 #'pat #'fender #'exp mod))
2410 (_ (syntax-violation 'syntax-case "invalid clause"
2411 (car clauses)))))))
2412
2413 (lambda (e r w s mod)
2414 (let ((e (source-wrap e w s mod)))
2415 (syntax-case e ()
2416 ((_ val (key ...) m ...)
2417 (if (and-map (lambda (x) (and (id? x) (not (ellipsis? x))))
2418 #'(key ...))
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
2424 'tmp x)
2425 #'(key ...) #'(m ...)
2426 r
2427 mod))
2428 (list (chi #'val r empty-wrap mod))))
2429 (syntax-violation 'syntax-case "invalid literals list" e))))))))
2430
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.
2440 (set! macroexpand
2441 (lambda (x . rest)
2442 (if (and (pair? x) (equal? (car x) noexpand))
2443 (cadr x)
2444 (let ((m (if (null? rest) 'e (car rest)))
2445 (esew (if (or (null? rest) (null? (cdr rest)))
2446 '(eval)
2447 (cadr rest))))
2448 (with-fluids ((*mode* m))
2449 (chi-top x null-env top-wrap m esew
2450 (cons 'hygiene (module-name (current-module)))))))))
2451
2452 (set! identifier?
2453 (lambda (x)
2454 (nonsymbol-id? x)))
2455
2456 (set! datum->syntax
2457 (lambda (id datum)
2458 (make-syntax-object datum (syntax-object-wrap id) #f)))
2459
2460 (set! syntax->datum
2461 ; accepts any object, since syntax objects may consist partially
2462 ; or entirely of unwrapped, nonsymbolic data
2463 (lambda (x)
2464 (strip x empty-wrap)))
2465
2466 (set! generate-temporaries
2467 (lambda (ls)
2468 (arg-check list? ls 'generate-temporaries)
2469 (map (lambda (x) (wrap (gensym-hook) top-wrap #f)) ls)))
2470
2471 (set! free-identifier=?
2472 (lambda (x y)
2473 (arg-check nonsymbol-id? x 'free-identifier=?)
2474 (arg-check nonsymbol-id? y 'free-identifier=?)
2475 (free-id=? x y)))
2476
2477 (set! bound-identifier=?
2478 (lambda (x y)
2479 (arg-check nonsymbol-id? x 'bound-identifier=?)
2480 (arg-check nonsymbol-id? y 'bound-identifier=?)
2481 (bound-id=? x y)))
2482
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
2489 (string-append
2490 (if who "~a: " "")
2491 "~a "
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))
2497 #f)))
2498
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.)
2504
2505 ;;; The expression is matched with the pattern as follows:
2506
2507 ;;; pattern: matches:
2508 ;;; () empty list
2509 ;;; any anything
2510 ;;; (<pattern>1 . <pattern>2) (<pattern>1 . <pattern>2)
2511 ;;; each-any (any*)
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?"
2517
2518 ;;; Vector cops out to pair under assumption that vectors are rare. If
2519 ;;; not, should convert to:
2520 ;;; #(vector <pattern>*) #(<pattern>*)
2521
2522 (let ()
2523
2524 (define match-each
2525 (lambda (e p w mod)
2526 (cond
2527 ((pair? e)
2528 (let ((first (match (car e) p w '() mod)))
2529 (and first
2530 (let ((rest (match-each (cdr e) p w mod)))
2531 (and rest (cons first rest))))))
2532 ((null? e) '())
2533 ((syntax-object? e)
2534 (match-each (syntax-object-expression e)
2535 p
2536 (join-wraps w (syntax-object-wrap e))
2537 (syntax-object-module e)))
2538 (else #f))))
2539
2540 (define match-each+
2541 (lambda (e x-pat y-pat z-pat w r mod)
2542 (let f ((e e) (w w))
2543 (cond
2544 ((pair? e)
2545 (call-with-values (lambda () (f (cdr e) w))
2546 (lambda (xr* y-pat r)
2547 (if r
2548 (if (null? y-pat)
2549 (let ((xr (match (car e) x-pat w '() mod)))
2550 (if xr
2551 (values (cons xr xr*) y-pat r)
2552 (values #f #f #f)))
2553 (values
2554 '()
2555 (cdr y-pat)
2556 (match (car e) (car y-pat) w r mod)))
2557 (values #f #f #f)))))
2558 ((syntax-object? e)
2559 (f (syntax-object-expression e) (join-wraps w e)))
2560 (else
2561 (values '() y-pat (match e z-pat w r mod)))))))
2562
2563 (define match-each-any
2564 (lambda (e w mod)
2565 (cond
2566 ((pair? e)
2567 (let ((l (match-each-any (cdr e) w mod)))
2568 (and l (cons (wrap (car e) w mod) l))))
2569 ((null? e) '())
2570 ((syntax-object? e)
2571 (match-each-any (syntax-object-expression e)
2572 (join-wraps w (syntax-object-wrap e))
2573 mod))
2574 (else #f))))
2575
2576 (define match-empty
2577 (lambda (p r)
2578 (cond
2579 ((null? p) r)
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))
2583 (else
2584 (case (vector-ref p 0)
2585 ((each) (match-empty (vector-ref p 1) r))
2586 ((each+) (match-empty (vector-ref p 1)
2587 (match-empty
2588 (reverse (vector-ref p 2))
2589 (match-empty (vector-ref p 3) r))))
2590 ((free-id atom) r)
2591 ((vector) (match-empty (vector-ref p 1) r)))))))
2592
2593 (define combine
2594 (lambda (r* r)
2595 (if (null? (car r*))
2596 r
2597 (cons (map car r*) (combine (map cdr r*) r)))))
2598
2599 (define match*
2600 (lambda (e p w r mod)
2601 (cond
2602 ((null? p) (and (null? e) r))
2603 ((pair? p)
2604 (and (pair? e) (match (car e) (car p) w
2605 (match (cdr e) (cdr p) w r mod)
2606 mod)))
2607 ((eq? p 'each-any)
2608 (let ((l (match-each-any e w mod))) (and l (cons l r))))
2609 (else
2610 (case (vector-ref p 0)
2611 ((each)
2612 (if (null? e)
2613 (match-empty (vector-ref p 1) r)
2614 (let ((l (match-each e (vector-ref p 1) w mod)))
2615 (and l
2616 (let collect ((l l))
2617 (if (null? (car l))
2618 r
2619 (cons (map car l) (collect (map cdr l)))))))))
2620 ((each+)
2621 (call-with-values
2622 (lambda ()
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)
2625 (and r
2626 (null? y-pat)
2627 (if (null? xr*)
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))
2632 ((vector)
2633 (and (vector? e)
2634 (match (vector->list e) (vector-ref p 1) w r mod))))))))
2635
2636 (define match
2637 (lambda (e p w r mod)
2638 (cond
2639 ((not r) #f)
2640 ((eq? p 'any) (cons (wrap e w mod) r))
2641 ((syntax-object? e)
2642 (match*
2643 (syntax-object-expression e)
2644 p
2645 (join-wraps w (syntax-object-wrap e))
2646 r
2647 (syntax-object-module e)))
2648 (else (match* e p w r mod)))))
2649
2650 (set! $sc-dispatch
2651 (lambda (e p)
2652 (cond
2653 ((eq? p 'any) (list e))
2654 ((syntax-object? 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)))))
2658
2659 ))
2660 )
2661
2662 (define-syntax with-syntax
2663 (lambda (x)
2664 (syntax-case x ()
2665 ((_ () e1 e2 ...)
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 ...)))))))
2672
2673 (define-syntax syntax-rules
2674 (lambda (x)
2675 (syntax-case x ()
2676 ((_ (k ...) ((keyword . pattern) template) ...)
2677 #'(lambda (x)
2678 ;; embed patterns as procedure metadata
2679 #((macro-type . syntax-rules)
2680 (patterns pattern ...))
2681 (syntax-case x (k ...)
2682 ((dummy . pattern) #'template)
2683 ...))))))
2684
2685 (define-syntax let*
2686 (lambda (x)
2687 (syntax-case x ()
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))))))))
2696
2697 (define-syntax do
2698 (lambda (orig-x)
2699 (syntax-case orig-x ()
2700 ((_ ((var init . step) ...) (e0 e1 ...) c ...)
2701 (with-syntax (((step ...)
2702 (map (lambda (v s)
2703 (syntax-case s ()
2704 (() v)
2705 ((e) #'e)
2706 (_ (syntax-violation
2707 'do "bad step expression"
2708 orig-x s))))
2709 #'(var ...)
2710 #'(step ...))))
2711 (syntax-case #'(e1 ...) ()
2712 (() #'(let doloop ((var init) ...)
2713 (if (not e0)
2714 (begin c ... (doloop step ...)))))
2715 ((e1 e2 ...)
2716 #'(let doloop ((var init) ...)
2717 (if e0
2718 (begin e1 e2 ...)
2719 (begin c ... (doloop step ...)))))))))))
2720
2721 (define-syntax quasiquote
2722 (letrec
2723 ((quasicons
2724 (lambda (x y)
2725 (with-syntax ((x x) (y y))
2726 (syntax-case #'y (quote list)
2727 ((quote dy)
2728 (syntax-case #'x (quote)
2729 ((quote dx) #'(quote (dx . dy)))
2730 (_ (if (null? #'dy)
2731 #'(list x)
2732 #'(cons x y)))))
2733 ((list . stuff) #'(list x . stuff))
2734 (else #'(cons x y))))))
2735 (quasiappend
2736 (lambda (x y)
2737 (with-syntax ((x x) (y y))
2738 (syntax-case #'y (quote)
2739 ((quote ()) #'x)
2740 (_ #'(append x y))))))
2741 (quasivector
2742 (lambda (x)
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))))))
2748 (quasi
2749 (lambda (p lev)
2750 (syntax-case p (unquote unquote-splicing quasiquote)
2751 ((unquote p)
2752 (if (= lev 0)
2753 #'p
2754 (quasicons #'(quote unquote)
2755 (quasi #'(p) (- lev 1)))))
2756 ((unquote . args)
2757 (= lev 0)
2758 (syntax-violation 'unquote
2759 "unquote takes exactly one argument"
2760 p #'(unquote . args)))
2761 (((unquote-splicing p) . q)
2762 (if (= lev 0)
2763 (quasiappend #'p (quasi #'q lev))
2764 (quasicons (quasicons #'(quote unquote-splicing)
2765 (quasi #'(p) (- lev 1)))
2766 (quasi #'q lev))))
2767 (((unquote-splicing . args) . q)
2768 (= lev 0)
2769 (syntax-violation 'unquote-splicing
2770 "unquote-splicing takes exactly one argument"
2771 p #'(unquote-splicing . args)))
2772 ((quasiquote p)
2773 (quasicons #'(quote quasiquote)
2774 (quasi #'(p) (+ lev 1))))
2775 ((p . q)
2776 (quasicons (quasi #'p lev) (quasi #'q lev)))
2777 (#(x ...) (quasivector (quasi #'(x ...) lev)))
2778 (p #'(quote p))))))
2779 (lambda (x)
2780 (syntax-case x ()
2781 ((_ e) (quasi #'e 0))))))
2782
2783 (define-syntax include
2784 (lambda (x)
2785 (define read-file
2786 (lambda (fn k)
2787 (let ((p (open-input-file fn)))
2788 (let f ((x (read p))
2789 (result '()))
2790 (if (eof-object? x)
2791 (begin
2792 (close-input-port p)
2793 (reverse result))
2794 (f (read p)
2795 (cons (datum->syntax k x) result)))))))
2796 (syntax-case x ()
2797 ((k filename)
2798 (let ((fn (syntax->datum #'filename)))
2799 (with-syntax (((exp ...) (read-file fn #'k)))
2800 #'(begin exp ...)))))))
2801
2802 (define-syntax include-from-path
2803 (lambda (x)
2804 (syntax-case x ()
2805 ((k filename)
2806 (let ((fn (syntax->datum #'filename)))
2807 (with-syntax ((fn (or (%search-load-path fn)
2808 (syntax-violation 'include-from-path
2809 "file not found in path"
2810 x #'filename))))
2811 #'(include fn)))))))
2812
2813 (define-syntax unquote
2814 (lambda (x)
2815 (syntax-case x ()
2816 ((_ e)
2817 (syntax-violation 'unquote
2818 "expression not valid outside of quasiquote"
2819 x)))))
2820
2821 (define-syntax unquote-splicing
2822 (lambda (x)
2823 (syntax-case x ()
2824 ((_ e)
2825 (syntax-violation 'unquote-splicing
2826 "expression not valid outside of quasiquote"
2827 x)))))
2828
2829 (define-syntax case
2830 (lambda (x)
2831 (syntax-case x ()
2832 ((_ e m1 m2 ...)
2833 (with-syntax
2834 ((body (let f ((clause #'m1) (clauses #'(m2 ...)))
2835 (if (null? clauses)
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 ...))
2845 (begin e1 e2 ...)
2846 rest))
2847 (_ (syntax-violation 'case "bad clause" x
2848 clause))))))))
2849 #'(let ((t e)) body))))))
2850
2851 (define-syntax identifier-syntax
2852 (lambda (x)
2853 (syntax-case x ()
2854 ((_ e)
2855 #'(lambda (x)
2856 #((macro-type . identifier-syntax))
2857 (syntax-case x ()
2858 (id
2859 (identifier? #'id)
2860 #'e)
2861 ((_ x (... ...))
2862 #'(e x (... ...)))))))))
2863
2864 (define-syntax define*
2865 (lambda (x)
2866 (syntax-case x ()
2867 ((_ (id . args) b0 b1 ...)
2868 #'(define id (lambda* args b0 b1 ...)))
2869 ((_ id val) (identifier? #'x)
2870 #'(define id val)))))