Debian Codegraph @

src/libmacro.scm

raw
1 ;;;
2 ;;; libmacro.scm - built-in macros
3 ;;;
4 ;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (select-module gauche)
35 (use util.match)
36 (declare (keep-private-macro cond-expand quasirename
37 syntax-error syntax-errorf
38 ^ ^_ ^a ^b ^c ^d ^e ^f ^g ^h ^i ^j ^k ^l ^m ^n
39 ^o ^p ^q ^r ^s ^t ^u ^v ^w ^x ^y ^z $ cut cute rec
40 guard check-arg
41 push! push-unique! pop! inc! dec! update! rotate!
42 let1 if-let1 and-let1 let/cc begin0 rlet1
43 let-values let*-values define-values set!-values
44 values-ref values->list
45 assume assume-type
46 dotimes dolist do-plist doplist
47 ecase typecase etypecase cond-list
48 define-condition-type condition
49 with-continuation-marks
50 unwind-protect
51 let-keywords let-keywords* let-optionals*
52 define-class define-generic define-method
53 lcons lcons* llist*
54 rxmatch-let rxmatch-if rxmatch-cond rxmatch-case
55 independently
56 define-compiler-macro))
57
58 ;; This file defines built-in macros.
59 ;; We need the compiler to be initialized at this stage.
60
61 ;;; cond-expand
62
63 (autoload gauche.version valid-version-spec? version-satisfy?)
64 (autoload gauche.package find-gauche-package-description)
65
66 (define-syntax cond-expand
67 (er-macro-transformer
68 (^[f r c]
69 (define features ((with-module gauche.internal cond-features)))
70 (define use. (r 'use))
71 (define begin. (r 'begin))
72 (define else. (r 'else))
73 (define allow-srfi-feature-id? #f)
74
75 ;; Check feature requirement. Returns #f if requirement is not
76 ;; satisfied. Returns a list of features to be use'd if requirement
77 ;; is satisfied (it can be an emptylist, if the requirement is fulfilled
78 ;; by Gauche built-in features).
79 (define (fulfill? req seed)
80 (cond
81 [(identifier? req)
82 (and-let1 p (assq (identifier->symbol req) features)
83 (unless allow-srfi-feature-id?
84 ((with-module gauche.internal %check-feature-id)
85 (car p)
86 (debug-source-info f)))
87 (if (null? (cdr p)) seed (cons (cadr p) seed)))]
88 [(not (pair? req)) (error "Invalid cond-expand feature-id:" req)]
89 [else
90 (case (unwrap-syntax (car req))
91 [(and) (fulfill-and (cdr req) seed)]
92 [(or) (fulfill-or (cdr req) seed)]
93 [(not) (fulfill-not (cadr req) seed)]
94 [(library) (fulfill-library (cdr req) seed)]
95 [(package) (fulfill-package (cdr req) seed)]
96 [else (error "Invalid cond-expand feature expression:" req)])]))
97
98 (define (fulfill-and reqs seed)
99 (if (null? reqs)
100 seed
101 (and-let1 c1 (fulfill? (car reqs) seed)
102 (fulfill-and (cdr reqs) c1))))
103
104 (define (fulfill-or reqs seed)
105 (if (null? reqs)
106 #f
107 (or (fulfill? (car reqs) seed)
108 (fulfill-or (cdr reqs) seed))))
109
110 (define (fulfill-not req seed)
111 (if (fulfill? req '()) #f seed))
112
113 (define (fulfill-library rest seed)
114 (unless (null? (cdr rest))
115 (error "Invalid feature requirement:" `(library ,@rest)))
116 (let* ([libname (car rest)]
117 [modname (cond
118 [(identifier? libname) (identifier->symbol libname)]
119 [(list? libname) (library-name->module-name libname)]
120 [else (error "Invalid library name in 'library' clause \
121 of cond-expand:" libname)])])
122 ;; NB: R7RS doesn't say we load the library implicitly.
123 (and (library-exists? modname)
124 seed)))
125
126 (define (fulfill-package rest seed)
127 (match rest
128 [(package)
129 (or (equal? package 'gauche)
130 (find-gauche-package-description package))]
131 [(package version-spec)
132 (unless (valid-version-spec? version-spec)
133 (error "Invalid version spec in package clause:" `(package ,@rest)))
134 (if (equal? package 'gauche)
135 (and (version-satisfy? version-spec (gauche-version)) seed)
136 (and-let1 gpd (find-gauche-package-description package)
137 (and (version-satisfy? version-spec (~ gpd'version)) seed)))]
138 [_ (error "Malformed package clause:" `(package ,@rest))]))
139
140 (define (rec cls)
141 (cond
142 [(null? cls) (error "Unfulfilled cond-expand (likely missing feature to run this code)")]
143 [(not (pair? (car cls)))
144 (error "Bad clause in cond-expand:" (car cls))]
145 [(c (r (caar cls)) else.)
146 (if (null? (cdr cls))
147 `(,begin. ,@(cdar cls))
148 (error "Misplaced else clause in cond-expand:" (car cls)))]
149 [(fulfill? (caar cls) '())
150 => (^[uses]
151 `(,begin. ,@(map (^[mod] `(,use. ,mod)) uses)
152 ,@(cdar cls)))]
153 [else (rec (cdr cls))]))
154
155 ;; :allow-srfi-feature-id is a hidden extension to skip checking
156 ;; of srfi-N feature identifier. They're deprecated and warned,
157 ;; but certain legacy srfis such as SRFI-7 that expands to cond-expand
158 ;; do not provide alternative (library (srfi N)) form. We only support
159 ;; such srfis for the legacy code, and it's simpler to use this
160 ;; compatibility mode rather than changing those srfis to use
161 ;; library clause.
162 (match f
163 [(_ ':allow-srfi-feature-id . clauses)
164 (set! allow-srfi-feature-id? #t)
165 (rec clauses)]
166 [(_ . clauses)
167 (rec clauses)]))))
168
169 ;; transitional
170 (with-module gauche.internal
171 (define (%check-feature-id sym source-info)
172 (let1 s (symbol->string sym)
173 (when (and (#/^srfi-\d+$/ s)
174 (not (vm-compiler-flag-is-set? SCM_COMPILE_SRFI_FEATURE_ID)))
175 (warn "Feature identifier '~a' is deprecated~a. Use (library ~a)\n"
176 sym
177 (if source-info
178 (format ", at ~s:~a" (car source-info) (cadr source-info))
179 "")
180 (regexp-replace #/^srfi-(\d+)$/ s "srfi.\\1"))))))
181
182 ;;; quasirename
183
184 (with-module gauche.internal
185 (define *quasirename-mode*
186 (and-let1 m (sys-getenv "GAUCHE_QUASIRENAME_MODE")
187 (cond [(equal? m "legacy") 'legacy]
188 [(equal? m "compatible") 'compatible]
189 [(equal? m "strict") 'strict]
190 [(equal? m "warn") 'warn]
191 [else (warn "Invalid GAUCHE_QUASIRENAME_MODE value; must be one \
192 of compatible, legacy, warn or strict, but got: ~s\n"
193 m)]))))
194
195 ;; NB: The walk code has the same structure as quasiquote expander; the
196 ;; output is different, however, and it's not so straightforward to refactor
197 ;; them. We'll eventually make a generic walker, but for now we have
198 ;; two separately.
199 (define-syntax quasirename
200 (er-macro-transformer
201 (^[f r c]
202 (define unquote. (r'unquote))
203 (define (unquote? x)
204 (and (identifier? x)
205 (c (r x) unquote.)))
206 (define unquote-splicing. (r'unquote-splicing))
207 (define (unquote-splicing? x)
208 (and (identifier? x)
209 (c (r x) unquote-splicing.)))
210 (define (unquote*? x)
211 (and (identifier? x)
212 (or (c (r x) unquote.)
213 (c (r x) unquote-splicing.))))
214 (define quasiquote. (r'quasiquote))
215 (define (quasiquote? x)
216 (and (identifier? x)
217 (c (r x) quasiquote.)))
218 (define cons. (r'cons))
219 (define extended-cons. (r'extended-cons))
220 (define list. (r'list))
221 (define append. (r'append))
222 (define vector. (r'vector))
223 (define list->vector. (r'list->vector))
224 (define let. (r'let))
225 (define rename. (r'rename))
226
227 ;; In the context where there's no outer list to which we intersperse to.
228 (define (quasi obj level)
229 (match obj
230 [((? quasiquote?) x)
231 (let1 xx (quasi x (+ level 1))
232 (if (eq? x xx)
233 obj
234 `(,list. 'quasiquote ,xx)))]
235 [((? unquote?) x)
236 (if (zero? level)
237 x
238 (let1 xx (quasi x (- level 1))
239 (if (eq? x xx)
240 obj
241 `(,list. ','unquote ,xx))))]
242 [((? unquote*? op) . xs) ;valid unquote is already handled
243 (if (zero? level)
244 (errorf "invalid ~a form in this context: ~s" op obj)
245 (let1 xxs (quasi* xs (- level 1))
246 (if (eq? xs xxs)
247 obj
248 `(,cons. ',op ,xxs))))]
249 [(? pair?) (quasi* obj level)]
250 [(? vector?) (quasi-vector obj level)]
251 [(? identifier?) `(,rename. ',obj)]
252 [_ `',obj]))
253
254 ;; In the spliceable context. objs is always a list.
255 ;; NB: we already excluded toplevel quasiquote and unquote
256 (define (quasi* objs level)
257 (match objs
258 [(((? unquote*? op) . xs) . ys)
259 (let1 yys (quasi* ys level)
260 (if (zero? level)
261 ((if (unquote? op) build build@) xs yys)
262 (let1 xxs (quasi* xs (- level 1))
263 (if (and (eq? xs xxs) (eq? ys yys))
264 obj
265 `(,cons. (,cons. ',op ,xxs) ,yys)))))]
266 [((? unquote*?) . _) ;`(... . ,xs) `(... . ,@xs)
267 (quasi objs level)]
268 [((? vector? x) . ys) (quasi-cons objs quasi-vector x ys level)]
269 [(x . ys) (quasi-cons objs quasi x ys level)]
270 [_ (quasi objs level)]))
271
272 (define (build objs rest)
273 (match objs
274 [() rest]
275 [(x . xs) `(,cons. ,x ,(build xs rest))]))
276
277 (define (build@ objs rest)
278 (match objs
279 [() rest]
280 [(x . xs) `(,append. ,x ,(build@ xs rest))]))
281
282 (define (quasi-cons objs quasi-car x ys level)
283 (let ([xx (quasi-car x level)]
284 [yys (quasi* ys level)])
285 (if (and (eq? x xx) (eq? ys yys))
286 objs
287 (if-let1 si (pair-attribute-get objs 'source-info #f)
288 (let1 orig (assoc-ref ((with-module gauche.internal %procedure-tags-alist) r)
289 'macro-input)
290 `(,extended-cons. ,xx ,yys '((source-info ,@si)
291 ,@(cond-list
292 [orig `(original . ,orig)]))))
293 `(,cons. ,xx ,yys)))))
294
295 (define (quasi-vector obj level)
296 (if (vector-has-splicing? obj)
297 `(,list->vector. ,(quasi* (vector->list obj) level))
298 (let* ([need-construct? #f]
299 [elts (map (^[elt] (rlet1 ee (quasi elt level)
300 (unless (eq? ee elt)
301 (set! need-construct? #t))))
302 (vector->list obj))])
303 (if need-construct?
304 `(,vector. ,@elts)
305 obj))))
306
307 (define (vector-has-splicing? obj)
308 (let loop ((i 0))
309 (cond [(= i (vector-length obj)) #f]
310 [(and (pair? (vector-ref obj i))
311 (unquote-splicing? (car (vector-ref obj i))))]
312 [else (loop (+ i 1))])))
313
314 (define (legacy-message f)
315 (if-let1 srcinfo (debug-source-info f)
316 (format "Legacy quasirename form (~a:~a): ~s"
317 (car srcinfo) (cadr srcinfo) f)
318 (format "Legacy quasirename form: ~s" f)))
319
320 (match f
321 [(_ rr ((? quasiquote? qq) ff))
322 (if (eq? (with-module gauche.internal *quasirename-mode*) 'legacy)
323 `(,let. ((,rename. ,rr))
324 ,(quasi `(,qq ,ff) 0))
325 `(,let. ((,rename. ,rr))
326 ,(quasi ff 0)))]
327 [(_ rr ff) ; old format
328 (case (with-module gauche.internal *quasirename-mode*)
329 [(warn) (let1 srcinfo (debug-source-info f)
330 (warn "~a\n" (legacy-message f)))]
331 [(strict) (let1 srcinfo (debug-source-info f)
332 (error (legacy-message f)))])
333 `(,let. ((,rename. ,rr))
334 ,(quasi ff 0))]
335 [_ (error "malformed quasirename:" f)]))))
336
337 ;;; syntax-error msg arg ...
338 ;;; syntax-errorf fmtstr arg ...
339 ;;; Signal an error at compile time.
340 ;;; These are typically used as a result of expansion of syntax-rules
341 ;;; macro; er-macro or legacy macro can directly call error/errorf so
342 ;;; there's no point to use syntax-error. Then, the 'original attribute
343 ;;; of the form contains the macro input that caused syntax error.
344 ;;; We extract that and throw a compound condition, so that the
345 ;;; error message will include the macro input that directly caused
346 ;;; this error.
347
348 (define-syntax syntax-error
349 (er-macro-transformer
350 (^[f r c]
351 (let ([args (map unwrap-syntax (cdr f))]
352 [original (pair-attribute-get f 'original #f)])
353 (if original
354 (raise (make-compound-condition
355 (apply make-error (car args) (cdr args))
356 (make <compile-error-mixin> :expr original)))
357 (apply error args))))))
358
359 (define-syntax syntax-errorf
360 (er-macro-transformer
361 (^[f r c]
362 (let ([args (map unwrap-syntax (cdr f))]
363 [original (pair-attribute-get f 'original #f)])
364 (if original
365 (raise (make-compound-condition
366 (make-error (apply format/ss (car args) (cdr args)))
367 (make <compile-error-mixin> :expr original)))
368 (apply errorf args))))))
369
370 ;;; ^ == lambda
371 (define-syntax ^
372 (er-macro-transformer
373 (^[f r c] (quasirename r `(lambda ,@(cdr f))))))
374
375 ;; (^x . body) == (lambda (x) . body) where x in #[a-z_]
376 ;; TODO: need to make 'lambda's hygineic!
377 (define-macro (^-generator var)
378 (let ([name (string->symbol (string-append "^" (symbol->string var)))])
379 `(define-syntax ,name
380 (er-macro-transformer
381 (^[f r c]
382 `(,,'(r'lambda) (,',var) ,@,'(cdr f)))))))
383 (define-macro (define-^x . vars)
384 `(begin ,@(map (lambda (x) `(^-generator ,x)) vars)))
385 (define-^x _ a b c d e f g h i j k l m n o p q r s t u v w x y z)
386
387 ;;; $
388
389 ;; Haskell-ish application.
390 ;; The starting '$' introduces the macro.
391 ;; Subsequent '$' delimits "one more arguments"
392 ;; Subsequent '$*' delimits "zero or more arguments".
393 ;;
394 ;; ($ f a b c) => (f a b c)
395 ;; ($ f a b c $) => (lambda (arg) (f a b c arg))
396 ;; ($ f $ g a b c) => (f (g a b c))
397 ;; ($ f $ g a b c $) => (lambda (arg) (f (g a b c arg)))
398 ;; ($ f $ g $ h a b c) => (f (g (h a b c)))
399 ;; ($ f a $ g b $ h c) => (f a (g b (h c)))
400 ;; ($ f a $ g b $ h $) => (lambda (arg) (f a (g b (h arg))))
401 ;;
402 ;; ($ f a b c $*) => (lambda args (apply f a b c args))
403 ;; == (pa$ f a b c)
404 ;; ($ f a b $* g c d) => (apply f a b (g c d))
405 ;; ($ f a b $* g c d $) => (lambda (arg) (apply f a b (g c d arg)))
406 ;; ($ f a b $* g c d $*) => (lambda args (apply f a b (apply g c d args)))
407 ;; ($ f a b $ g c d $*) => (lambda args (f a b (apply g c d args)))
408
409 (define-syntax $
410 (er-macro-transformer
411 (^[f r c]
412 (define $. (r '$))
413 (define $*. (r '$*))
414
415 ;; ($ x y $ ...) => (x y ($-fold ...))
416 ;; last-arg has gensym'd symbol used as the outermost lambda arg.
417 ;; it is passed only when lis ends with $ or $*.
418 (define ($-fold lis rargs last-arg)
419 (cond
420 [(null? lis) (reverse rargs)]
421 [(c (car lis) $.)
422 (if (null? (cdr lis))
423 (reverse rargs `(,last-arg))
424 (reverse rargs `(,($-fold (cdr lis) '() last-arg))))]
425 [(c (car lis) $*.)
426 (if (null? (cdr lis))
427 (cons (r'apply) (reverse rargs `(,last-arg)))
428 (cons (r'apply) (reverse rargs `(,($-fold (cdr lis) '() last-arg)))))]
429 [else ($-fold (cdr lis) (cons (car lis) rargs) last-arg)]))
430
431 (if (null? (cdr f))
432 (error "malformed $ form:" f)
433 (let1 x (last f)
434 (cond [(c x $.)
435 (let1 arg (gensym)
436 `(,(r'lambda) (,arg) ,($-fold (cdr f) '() arg)))]
437 [(c x $*.)
438 (let1 arg (gensym)
439 `(,(r'lambda) ,arg ,($-fold (cdr f) '() arg)))]
440 [else ($-fold (cdr f) '() #f)]))))))
441
442 ;;; cut, cute (SRFI-26)
443
444 (define-syntax cut
445 (er-macro-transformer
446 (^[f r c]
447 (define <>. (r '<>))
448 (define <...>. (r '<...>))
449 ;; returns list of tmp args and list of original items in which
450 ;; placeholders are replaced with tmp vars
451 (define (scan args tmps elts)
452 (cond [(null? args) (values (reverse tmps) (reverse elts))]
453 [(not (pair? args)) (error "Malformed cut:" f)]
454 [(c (car args) <...>.)
455 (if (null? (cdr args))
456 (let1 restarg (gensym)
457 (values (reverse tmps restarg)
458 (cons (r'apply) (reverse elts (list restarg)))))
459 (error "Malformed cut:" f))]
460 [(c (car args) <>.)
461 (let1 t (gensym)
462 (scan (cdr args) (cons t tmps) (cons t elts)))]
463 [else
464 (scan (cdr args) tmps (cons (car args) elts))]))
465 (receive (tmps elts) (scan (cdr f) '() '())
466 `(,(r'lambda) ,tmps ,elts)))))
467
468 (define-syntax cute
469 (er-macro-transformer
470 (^[f r c]
471 (define <>. (r '<>))
472 (define <...>. (r '<...>))
473 ;; returns three lists: list of tmp args, list of bindings
474 ;; and list of all tmp vars
475 (define (scan args tmps binds elts)
476 (cond [(null? args)
477 (values (reverse tmps) (reverse binds) (reverse elts))]
478 [(not (pair? args)) (error "Malformed cute:" f)]
479 [(c (car args) <...>.)
480 (if (null? (cdr args))
481 (let1 restarg (gensym)
482 (values (reverse tmps restarg)
483 (reverse binds)
484 (cons (r'apply) (reverse elts (list restarg)))))
485 (error "Malformed cute:" f))]
486 [(c (car args) <>.)
487 (let1 t (gensym)
488 (scan (cdr args) (cons t tmps) binds (cons t elts)))]
489 [else
490 (let1 t (gensym)
491 (scan (cdr args) tmps `((,t ,(car args)) ,@binds) (cons t elts)))]))
492 (receive (tmps binds elts) (scan (cdr f) '() '() '())
493 `(,(r'letrec) ,binds
494 (,(r'lambda) ,tmps ,elts))))))
495
496 ;;; rec (SRFI-31)
497
498 (define-syntax rec
499 (er-macro-transformer
500 (^[f r c]
501 (match f
502 [(_ (name . formals) . body)
503 (quasirename r
504 `(letrec ((,name (lambda ,formals ,@body))) ,name))]
505 [(_ name expr)
506 (quasirename r
507 `(letrec ((,name ,expr)) ,name))]
508 [_ (error "malformed rec:" f)]))))
509
510 ;;; guard (SRFI-34)
511
512 (define-syntax guard
513 (er-macro-transformer
514 (^[f r c]
515 (define %reraise. ((with-module gauche.internal make-identifier)
516 '%reraise
517 (find-module 'gauche.internal)
518 '()))
519 (match f
520 [(_ (var clause ...) body ...)
521 (unless (every list? clause)
522 (error "malformed guard clauses:" f))
523 (if (and (pair? clause)
524 (c (r'else) (car (last clause))))
525 (quasirename r
526 `(with-error-handler
527 (lambda (,var)
528 (cond ,@clause))
529 (lambda () ,@body)
530 :rewind-before #t))
531 (quasirename r
532 `(with-error-handler
533 (lambda (,var)
534 (cond ,@clause
535 (else (,%reraise.))))
536 (lambda () ,@body)
537 :rewind-before #t)))]
538 [_ (error "malformed guard:" f)]))))
539
540 ;;; check-arg
541
542 (define-syntax check-arg
543 (er-macro-transformer
544 (^[f r c]
545 (match f
546 [(_ test arg)
547 (quasirename r
548 `(let ((tmp ,arg))
549 (unless (,test tmp)
550 (errorf "bad type of argument for ~s: ~s" 'arg tmp))))]
551 [_ (error "malformed check-arg:" f)]))))
552
553 ;;; bind construct
554
555 (define-syntax let1 ;single variable bind
556 (er-macro-transformer
557 (^[f r c]
558 (match f
559 [(_ var exp . body) (quasirename r
560 `(let ((,var ,exp)) ,@body))]
561 [_ (error "malformed let1:" f)]))))
562
563 (define-syntax if-let1 ;like aif in On Lisp, but explicit var
564 (er-macro-transformer
565 (^[f r c]
566 (match f
567 [(_ var exp then . else) (quasirename r
568 `(let ((,var ,exp)) (if ,var ,then ,@else)))]
569 [_ (error "malformed if-let1:" f)]))))
570
571 (define-syntax and-let1 ;returns #f if test evaluates #f
572 (er-macro-transformer
573 (^[f r c]
574 (match f
575 [(_ var test exp . more) (quasirename r
576 `(let ((,var ,test))
577 (and ,var (begin ,exp ,@more))))]
578 [_ (error "malformed and-let1:" f)]))))
579
580 (define-syntax let/cc ;as in PLT
581 (er-macro-transformer
582 (^[f r c]
583 (match f
584 [(_ var . body) (quasirename r
585 `(call/cc (lambda (,var) ,@body)))]
586 [_ (error "malformed let/cc:" f)]))))
587
588 (define-syntax begin0 ;prog1 in Lisp
589 (er-macro-transformer
590 (^[f r c]
591 (match f
592 [(_ exp . more) (quasirename r
593 `(receive res ,exp ,@more (apply values res)))]
594 [_ (error "malformed begin0:" f)]))))
595
596 (define-syntax rlet1 ;begin0 + let1
597 (er-macro-transformer
598 (^[f r c]
599 (match f
600 [(_ var exp . body) (quasirename r
601 `(let ((,var ,exp)) ,@body ,var))]
602 [_ (error "malformed rlet1:" r)]))))
603
604 (define-syntax let-values
605 (er-macro-transformer
606 (^[f r c]
607 ;; we rename all the formals and rebind
608 (match f
609 [(_ ((formals init) ...) . body)
610 (let* ([formals* (map (^f (map* (^x (gensym (x->string x)))
611 (^t (if (null? t) t (gensym (x->string t))))
612 f))
613 formals)]
614 [rebinds (append-map
615 (^[f f*]
616 (map* list
617 (^[a b] (if (null? a) '() (list (list a b))))
618 f f*))
619 formals formals*)])
620 (quasirename r
621 `(let*-values ,(map list formals* init)
622 (let ,rebinds
623 ,@body))))]))))
624
625 (define-syntax let*-values
626 (er-macro-transformer
627 (^[f r c]
628 (match f
629 [(_ () . body) (quasirename r
630 `(let () ,@body))]
631 [(_ ((formals init) . rest) . body)
632 (quasirename r
633 `(receive ,formals ,init
634 (let*-values ,rest ,@body)))]))))
635
636 (define-syntax define-values
637 (er-macro-transformer
638 (^[f r c]
639 ;; (define-values (a b ... z) expr)
640 ;; => (begin (define a (undefined))
641 ;; ...
642 ;; (define z (receive (a' ... z') expr
643 ;; (set! a a') ...
644 ;; z')
645 (match f
646 [(_ formals expr)
647 (match formals
648 [() ; allowed in r7rs
649 (quasirename r
650 `(define ,(gensym) (receive ,(gensym) ,expr #f)))]
651 [(v) ; trivial case
652 (quasirename r
653 `(define ,v ,expr))]
654 [(_ ...)
655 (let ([vs (drop-right formals 1)]
656 [tmps (map (^_ (gensym)) formals)])
657 `(,(r'begin)
658 ,@(map (^v `(,(r'define) ,v (,(r'undefined)))) vs)
659 (,(r'define) ,(last formals)
660 (,(r'receive) ,tmps ,expr
661 ,@(map (^[v t] `(,(r'set!) ,v ,t)) vs tmps)
662 ,(last tmps)))))]
663 [(? pair?) ; improper list
664 (let* ([vs (drop-right formals 0)]
665 [tmps (map* (^_ (gensym)) (^_ (gensym)) formals)])
666 `(,(r'begin)
667 ,@(map (^v `(,(r'define) ,v (,(r'undefined)))) vs)
668 (,(r'define) ,(cdr (last-pair formals))
669 (,(r'receive) ,tmps ,expr
670 ,@(map (^[v t] `(,(r'set!) ,v ,t)) vs tmps)
671 ,(cdr (last-pair tmps))))))]
672 [v ; single variable
673 (let1 tmp (gensym)
674 (quasirename r
675 `(define ,v (receive ,tmp ,expr ,tmp))))])]))))
676
677 (define-syntax set!-values
678 (er-macro-transformer
679 (^[f r c]
680 (match f
681 [(_ formals expr)
682 (let1 tmps (map* (^_ (gensym)) (^r (if (null? r) r (gensym))) formals)
683 (quasirename r
684 `(receive ,tmps ,expr
685 ,@(map* (^[v t] (quasirename r `(set! ,v ,t)))
686 (^[v t] (if (null? v)
687 '()
688 (quasirename r `((set! ,v ,t)))))
689 formals tmps)
690 (undefined))))]
691 [_ (error "Malformed set!-values:" f)]))))
692
693 (define-syntax values-ref
694 (er-macro-transformer
695 (^[f r c]
696 ;; we provide shortcut for common cases
697 (match f
698 [(_ mv-expr n)
699 (if (and (exact-integer? n) (<= n 5))
700 (let1 vars (map (^_ (gensym)) (iota (+ n 1)))
701 (quasirename r
702 `(receive (,@vars . _) ,mv-expr ,(last vars))))
703 (quasirename r
704 `(receive vals ,mv-expr (list-ref vals ,n))))]
705 [(_ mv-expr n m)
706 (if (and (exact-integer? n) (<= n 5)
707 (exact-integer? m) (<= m 5))
708 (let* ([vars (map (^_ (gensym)) (iota (+ (max n m) 1)))]
709 [vn (list-ref vars n)]
710 [vm (list-ref vars m)])
711 (quasirename r
712 `(receive (,@vars . _) ,mv-expr (values ,vn ,vm))))
713 (quasirename r
714 `(receive vals ,mv-expr (values (list-ref vals ,n)
715 (list-ref vals ,m)))))]
716 [(_ mv-expr ns ...)
717 (if (null? ns)
718 (error "malformed values-ref:" f)
719 (if (and (every exact-integer? ns)
720 (every (cut <= <> 5) ns))
721 (let* ([vars (map (^_ (gensym)) (iota (+ (apply max ns) 1)))]
722 [rvars (map (^k (list-ref vars k)) ns)])
723 (quasirename r
724 `(receive (,@vars . _) ,mv-expr (values ,@rvars))))
725 (quasirename r
726 `(receive vals ,mv-expr
727 (apply values (map (^[i] (list-ref vals i))
728 (list ,@(cons n ns))))))))]))))
729
730 (define-syntax values->list
731 (er-macro-transformer
732 (^[f r c]
733 (match f
734 [(_ mv-expr) (quasirename r
735 `(receive x ,mv-expr x))]))))
736
737 ;;; generalized set! family
738
739 (define-syntax push!
740 (er-macro-transformer
741 (^[f r c]
742 (match f
743 [(_ (proc arg ...) val)
744 (let1 vars (map (^_ (gensym)) arg)
745 (quasirename r
746 `(let [(getter ,proc) ,@(map list vars arg)]
747 ((setter getter) ,@vars (cons ,val (getter ,@vars))))))]
748 [(_ loc val)
749 (quasirename r
750 `(set! ,loc (cons ,val ,loc)))]
751 [_ (error "malformed push!:" f)]))))
752
753 (define-syntax push-unique!
754 (er-macro-transformer
755 (^[f r c]
756 (match f
757 [(_ p val) (quasirename r `(push-unique! ,p ,val eqv?))]
758 [(_ (proc arg ...) val equal)
759 (let1 vars (map (^_ (gensym)) arg)
760 (quasirename r
761 `(let ([val ,val]
762 [getter ,proc]
763 ,@(map list vars arg))
764 (let1 vs (getter ,@vars)
765 (unless (member val vs ,equal)
766 ((setter getter) ,@vars (cons val vs)))))))]
767 [(_ loc val equal)
768 (quasirename r
769 `(let ([val ,val]
770 [vs ,loc])
771 (unless (member val vs ,equal)
772 (set! ,loc (cons val vs)))))]
773 [_ (error "malformed push-unique!:" f)]))))
774
775 (define-syntax pop!
776 (er-macro-transformer
777 (^[f r c]
778 (match f
779 [(_ (proc arg ...))
780 (let1 vars (map (^_ (gensym)) arg)
781 (quasirename r
782 `(let ([getter ,proc] ,@(map list vars arg))
783 (let1 val (getter ,@vars)
784 ((setter getter) ,@vars (cdr val))
785 (car val)))))]
786 [(_ loc)
787 (quasirename r
788 `(let1 val ,loc
789 (set! ,loc (cdr val))
790 (car val)))]
791 [_ (error "malformed pop!:" f)]))))
792
793 (define-syntax inc!
794 (er-macro-transformer
795 (^[f r c]
796 (define (gen proc arg delta)
797 (let1 vars (map (^_ (gensym)) arg)
798 (quasirename r
799 `(let ([getter ,proc] ,@(map list vars arg))
800 ((setter getter) ,@vars (+ (getter ,@vars) ,delta))))))
801 (match f
802 [(_ (proc arg ...) delta) (gen proc arg delta)]
803 [(_ (proc arg ...)) (gen proc arg 1)]
804 [(_ loc delta) (quasirename r
805 `(set! ,loc (+ ,loc ,delta)))]
806 [(_ loc) (quasirename r
807 `(set! ,loc (+ ,loc 1)))]
808 [_ (error "malformed inc!:" f)]))))
809
810 (define-syntax dec!
811 (er-macro-transformer
812 (^[f r c]
813 (define (gen proc arg delta)
814 (let1 vars (map (^_ (gensym)) arg)
815 (quasirename r
816 `(let ([getter ,proc] ,@(map list vars arg))
817 ((setter getter) ,@vars (- (getter ,@vars) ,delta))))))
818 (match f
819 [(_ (proc arg ...) delta) (gen proc arg delta)]
820 [(_ (proc arg ...)) (gen proc arg 1)]
821 [(_ loc delta) (quasirename r
822 `(set! ,loc (- ,loc ,delta)))]
823 [(_ loc) (quasirename r
824 `(set! ,loc (- ,loc 1)))]
825 [_ (error "malformed dec!:" f)]))))
826
827 (define-syntax update!
828 (er-macro-transformer
829 (^[f r c]
830 (match f
831 [(_ (proc arg ...) updater val ...)
832 (let1 vars (map (^_ (gensym)) arg)
833 (quasirename r
834 `(let ([getter ,proc] ,@(map list vars arg))
835 ((setter getter) ,@vars (,updater ,@val (getter ,@vars))))))]
836 [(_ loc updater val ...)
837 (quasirename r
838 `(set! ,loc (,updater ,@val ,loc)))]
839 [_ (error "malformed update!:" f)]))))
840
841 (define-syntax rotate!
842 (er-macro-transformer
843 (^[f r c]
844 ;; Returns
845 ;; - list of bindings
846 ;; - expression to get value
847 ;; - a procedure returns an expression to set value
848 (define (gen-bind loc)
849 (match loc
850 [(proc arg ...)
851 (let ([gettervar (gensym)]
852 [argvars (map (^_ (gensym)) arg)])
853 (values `((,gettervar ,proc) ,@(map list argvars arg))
854 `(,gettervar ,@argvars)
855 (^[val] (quasirename r
856 `((setter ,gettervar) ,@argvars ,val)))))]
857 [loc (values '()
858 loc
859 (^[val] (quasirename r
860 `(set! ,loc ,val))))]))
861 (if (null? (cdr f))
862 (quasirename r `(begin)) ; special case
863 (let loop ([binds '()]
864 [getters '()]
865 [setter-gens '()]
866 [locs (cdr f)])
867 (if (null? locs)
868 (let ([getters-rot (let* ([tail (list #f)]
869 [r (reverse getters tail)])
870 (set! (car tail) (car r))
871 (cdr r))]
872 [tmps (map (^_ (gensym)) getters)])
873 (quasirename r
874 `(let ,(concatenate (reverse binds))
875 (let ,(map list tmps getters-rot)
876 ,@(map (^[gen tmp] (gen tmp)) (reverse setter-gens) tmps)))))
877 (receive (b g s) (gen-bind (car locs))
878 (loop (cons b binds)
879 (cons g getters)
880 (cons s setter-gens)
881 (cdr locs))))))
882 )))
883
884 ;;; assume (SRFI-145) and co.
885
886 ;; We might add run-time optimization switch to expand assume to nothing.
887 (define-syntax assume
888 (er-macro-transformer
889 (^[f r c]
890 (match f
891 [(_ expr)
892 (quasirename r
893 `(or ,expr
894 (error (format "Invalid assumption: ~s" ',expr))))]
895 [(_ expr msg . objs)
896 (quasirename r
897 `(or ,expr
898 (error ,msg ,@objs)))]))))
899
900 ;; This will eventually folded into the compiler. The argumet must be
901 ;; a literal <type>.
902 (define-syntax assume-type
903 (er-macro-transformer
904 (^[f r c]
905 (match f
906 [(_ expr type)
907 (quasirename r
908 `(let1 v ,expr
909 (if (of-type? v ,type)
910 v
911 (type-error ',expr ,type v))))]
912 [(_ expr type msg . objs)
913 (quasirename r
914 `(let1 v ,expr
915 (if (of-type? v ,type)
916 v
917 (error ,msg ,@objs))))]))))
918
919 ;;; repeat construct
920
921 (define-syntax dotimes
922 (er-macro-transformer
923 (^[f r c]
924 (define (expand var n res body)
925 (let1 limit (gensym "limit")
926 (quasirename r
927 `(do ([,limit ,n]
928 [,var 0 (+ ,var 1)])
929 [(>= ,var ,limit) ,res]
930 ,@body))))
931 (match f
932 [(_ (var n res) . body) (expand var n res body)]
933 [(_ (var n) . body) (expand var n (undefined) body)]
934 [(_ (n) . body)
935 ;; gauche extension. we special-case when n is inf.0 to avoid
936 ;; unnecessary flonum calculation
937 (quasirename r
938 `(let1 i ,n
939 (cond [(<= i 0) (undefined)]
940 [(infinite? i) (do () (#f) ,@body)]
941 [else
942 ,(expand (gensym) n (undefined) body)])))]
943 [_ (error "Malformed dotimes:" f)]))))
944
945 (define-syntax dolist
946 (er-macro-transformer
947 (^[f r c]
948 (define (expand var lis res body)
949 (let1 p (gensym "p")
950 (quasirename r
951 `(do ([,p ,lis (cdr ,p)])
952 [(null? ,p)
953 (let1 ,var '() ,res)] ;bound var for CL compatibility
954 (let1 ,var (car ,p) ,@body)))))
955 (match f
956 [(_ (var lis res) . body) (expand var lis res body)]
957 [(_ (var lis) . body) (expand var lis (undefined) body)]
958 [(_ (lis) . body) (expand (gensym) lis (undefined) body)]
959 [_ (error "Malformed dolist:" f)]))))
960
961 (define-syntax do-plist
962 (er-macro-transformer
963 (^[f r c]
964 (define (expand k v plis body default)
965 (quasirename r
966 `(do ([e (^[,k ,v] ,@body)]
967 [p ,plis (cddr p)])
968 [(cond [(null? p) #t]
969 [(null? (cdr p)) (e (car p) ,default)]
970 [else #f])]
971 (e (car p) (cadr p)))))
972 (match f
973 [(_ ((k v) plis default) . body)
974 (expand k v plis body default)]
975 [(_ ((k v) plis) . body)
976 (expand k v plis body
977 (quasirename r `(error "plist is not even:" ,plis)))]
978 [_ (error "Malformed do-plist:" f)]))))
979
980 (define-syntax doplist do-plist) ;for backward compatibility
981
982 ;;; ecase, a la CL
983
984 (define-syntax ecase
985 (er-macro-transformer
986 (^[f r c]
987 (match f
988 [(_ expr clause ...)
989 (or (and-let* ([ (pair? clause) ]
990 [last-clause (last clause)]
991 [ (pair? last-clause) ]
992 [ (c (r'else) (car last-clause)) ])
993 ;; If there's an else, ecase is the same as case.
994 (quasirename r
995 `(case ,expr ,@clause)))
996 (let1 choices (append-map car clause)
997 (quasirename r
998 `(let ([v ,expr])
999 (case v
1000 ,@clause
1001 (else (errorf "ecase test fell through: got ~s, \
1002 expecting one of ~s" v ',choices)))))))]
1003 [_ (error "Malformed ecase:" f)]))))
1004
1005 ;;; typecase, a la CL
1006
1007 ;; NB: Eventually typecase should be recognized by the compiler so that
1008 ;; - The compiler can inference and propagate type information of expr
1009 ;; - The compiler can do better job for dispatching on built-in types
1010 ;; rather than using generic type-of?.
1011 (define-syntax typecase
1012 (er-macro-transformer
1013 (^[f r c]
1014 (match f
1015 [(_ expr clause ...)
1016 (let1 v (gensym)
1017 (define (clauses cs)
1018 (match cs
1019 [() (undefined)]
1020 [((type-expr expr ...) . rest)
1021 (if (c (r'else) type-expr)
1022 (if (null? rest)
1023 (quasirename r `(begin ,@expr))
1024 (error "'else' clause isn't at the end:" f))
1025 (quasirename r
1026 `(if (of-type? ,v ,type-expr)
1027 (begin ,@expr)
1028 ,(clauses rest))))]
1029 [_ (error "Malformed clause in " f)]))
1030 (quasirename r
1031 `(let ([,v ,expr]) ,(clauses clause))))]
1032 [_ (error "Malformed typecase:" f)]))))
1033
1034 (define-syntax etypecase
1035 (er-macro-transformer
1036 (^[f r c]
1037 (match f
1038 [(_ expr clause ...)
1039 (if (find (^[cl] (and (pair? cl) (c (r'else) (car cl)))) clause)
1040 (quasirename r
1041 `(typecase ,expr ,@clause))
1042 (quasirename r
1043 `(let ((v ,expr))
1044 (typecase v ,@clause
1045 (else
1046 (errorf "etypecase fell through: expecting one of \
1047 types in ~s, but got ~s"
1048 (map car '(,@clause)) v))))))]
1049 [_ (error "Malformed etypecase:" f)]))))
1050
1051 ;;; cond-list - a syntax to construct a list
1052
1053 ;; (cond-list clause clause2 ...)
1054 ;;
1055 ;; clause : (test expr ...)
1056 ;; | (test => proc)
1057 ;; | (test @ expr ...) ;; splice
1058 ;; | (test => @ proc) ;; splice
1059
1060 (define-syntax cond-list
1061 (er-macro-transformer
1062 (^[f r c]
1063 (let ([=>. (r '=>)]
1064 (@. (r '@)))
1065 (match f
1066 [(_) '()]
1067 [(_ (test) . rest)
1068 (quasirename r
1069 `(let* ([tmp ,test]
1070 [r (cond-list ,@rest)])
1071 (if tmp (cons tmp r) r)))]
1072 [(_ (test (? (cut c <> =>.)) proc) . rest)
1073 (quasirename r
1074 `(let* ([tmp ,test]
1075 [r (cond-list ,@rest)])
1076 (if tmp (cons (,proc tmp) r) r)))]
1077 [(_ (test (? (cut c <> =>.)) (? (cut c <> @.)) proc) . rest)
1078 (quasirename r
1079 `(let* ([tmp ,test]
1080 [r (cond-list ,@rest)])
1081 (if tmp (append (,proc tmp) r) r)))]
1082 [(_ (test (? (cut c <> @.)) expr ...) . rest)
1083 (quasirename r
1084 `(let* ([tmp ,test]
1085 [r (cond-list ,@rest)])
1086 (if tmp (append (begin ,@expr) r) r)))]
1087 [(_ (test expr ...) . rest)
1088 (quasirename r
1089 `(let* ([tmp ,test]
1090 [r (cond-list ,@rest)])
1091 (if tmp (cons (begin ,@expr) r) r)))]
1092 )))))
1093
1094 ;;; SRFI-35 condition macros
1095
1096 ;; we extend SRFI-35 to allow #f as predicate and accessors, as well as
1097 ;; omitting accessors.
1098
1099 (define-syntax define-condition-type
1100 (er-macro-transformer
1101 (^[f r c]
1102 (match (cdr f)
1103 [(name super pred . field-specs)
1104 (define (badfield-error field)
1105 (error "bad field spec for define-condition-type:" field))
1106 (define (scan-specs specs slots readers)
1107 (match specs
1108 [() (emit-defs slots readers)]
1109 [((field #f) . rest)
1110 (scan-specs rest (cons field slots) readers)]
1111 [((field) . rest)
1112 (scan-specs rest (cons field slots) readers)]
1113 [((field reader) . rest)
1114 (scan-specs rest (cons field slots)
1115 (cons (quasirename r
1116 `(define (,reader obj)
1117 (condition-ref obj ',field)))
1118 readers))]
1119 [_ (badfield-error (car specs))]))
1120 (define (emit-defs slots readers)
1121 (quasirename r
1122 `(begin
1123 (define-class ,name (,super)
1124 ,(map (^s (quasirename r
1125 `(,s :init-keyword ',(make-keyword s))))
1126 slots)
1127 :metaclass <condition-meta>)
1128 ,@readers
1129 ,@(if pred
1130 (quasirename r
1131 `((define (,pred obj)
1132 (condition-has-type? obj ,name))))
1133 '()))))
1134 (scan-specs field-specs '() '())]
1135 ))))
1136
1137 (define-syntax condition
1138 (er-macro-transformer
1139 (^[f r c]
1140 (match f
1141 [(_ type-field-binding ...)
1142 (quasirename r
1143 `(make-compound-condition
1144 ,@(map (match-lambda
1145 [(type (field expr) ...)
1146 (quasirename r
1147 `(make-condition
1148 ,type
1149 ,@(append-map (^[f e] `(',f ,e)) field expr)))]
1150 [_ (error "malformed condition:" f)])
1151 type-field-binding)))]
1152 [_ (error "malformed condition:" f)]))))
1153
1154 ;;; continuation marks
1155
1156 (define-syntax with-continuation-marks
1157 (er-macro-transformer
1158 (^[f r c]
1159 (match f
1160 [(_ () . body) (quasirename r `(let () ,@body))]
1161 [(_ ((key val) . rest) . body)
1162 (quasirename r
1163 `(with-continuation-mark ,key ,val
1164 (with-continuation-marks ,rest ,@body)))]
1165 [_ (error "malformed with-continuation-marks:" f)]))))
1166
1167
1168 ;;; unwind-protect
1169
1170 ;; HANDLERS are called when BODY exits, either normally or abnormally. This
1171 ;; is convenient if you have cleanup tasks you want to execute after BODY.
1172 ;;
1173 ;; Note that we don't call HANDLERS if control jumps out from BODY by
1174 ;; calling a continuation captured outside of unwind-protect; in such case
1175 ;; the control may return into BODY later.
1176 ;;
1177 ;; Once HANDLERS are executed, the resources needed in BODY may no longer
1178 ;; available. However, we don't prohibit reentering BODY again, since
1179 ;; there may be a delimited continuation that can be reexecuted within
1180 ;; the dynamic environment of BODY. If the control falls out from BODY
1181 ;; (either normally or abnormally) second time or later, HANDLERS will
1182 ;; no longer be executed.
1183 ;;
1184 ;; We also tweak exit-handler parameter inside the dyanmic scope of BODY
1185 ;; to ensure HANDLERS are executed even if BODY calls exit.
1186 ;; (An alternative idea is to treat exit as if it's another kind of a
1187 ;; condition, so that guard clauses are invoked. We tried it, but the
1188 ;; problem is how to deal with "ignore-errors" idiom,
1189 ;; e.g. (guard (e [else #f]) body). The exit condition shouldn't be
1190 ;; stopped in such a way.)
1191 ;;
1192 ;; TODO: Current definition doesn't work when unwind-protect is used
1193 ;; within a thread that is terminated; thread termination isn't a condition
1194 ;; either.
1195
1196 ;; The source-info argument isn't used now, but could be useful for
1197 ;; troubleshooting. We use keyword arguments so that we can enhance
1198 ;; %unwind-protect later without breaking existing precompiled code
1199 ;; that alreay has call to %unwind-protect embedded as the result of
1200 ;; expansion.
1201 (define-syntax unwind-protect
1202 (er-macro-transformer
1203 (^[f r c]
1204 (match f
1205 [(_ body handlers ...)
1206 ;; Some trick to hide %unwind-protect in gauche.internal
1207 (let* ([sinfo (debug-source-info f)]
1208 [lambda. (r 'lambda)]
1209 [%unwind-protect. ((with-module gauche.internal make-identifier)
1210 '%unwind-protect
1211 (find-module 'gauche.internal)
1212 '())])
1213 (if sinfo
1214 `(,%unwind-protect. (,lambda. () ,body) (,lambda. () ,@handlers)
1215 ':source-info ',sinfo)
1216 `(,%unwind-protect. (,lambda. () ,body) (,lambda. () ,@handlers))))]
1217 [_ (error "Malformed unwind-protect:" f)]))))
1218
1219 (select-module gauche.internal)
1220 (define (%unwind-protect thunk handlers :key (source-info #f))
1221 (let ([x (exit-handler)]
1222 [done #f])
1223 (define (cleanup)
1224 (unless done
1225 (set! done #t)
1226 (handlers)))
1227 (with-error-handler
1228 (lambda (e)
1229 (exit-handler x)
1230 (cond
1231 [(condition-has-type? e <serious-condition>)
1232 (cleanup)
1233 ;; NB: We don't know E is thrown by r7rs#raise or
1234 ;; r7rs#raise-continuable, but gauche#raise can handle both
1235 ;; case.
1236 (raise e)]
1237 [else
1238 ;; exception handler can return to the caller
1239 ((with-module gauche.internal %reraise))]))
1240 (lambda ()
1241 (receive r
1242 (dynamic-wind
1243 (lambda ()
1244 (exit-handler (lambda (code fmt args)
1245 (cleanup)
1246 (x code fmt args))))
1247 thunk
1248 (lambda () (exit-handler x)))
1249 (cleanup)
1250 (apply values r)))
1251 :rewind-before #t)))
1252
1253 ;;; Extended argument parsing
1254
1255 ;; Extended lambda formals (:optional, :key, :rest etc) are
1256 ;; expanded into the call of let-optionals* and let-keywords*
1257 ;; macros within the compiler. Eventually the handling of the
1258 ;; optional and keyword arguments will be built in the VM.
1259
1260 (select-module gauche)
1261 (define-syntax let-optionals*
1262 (er-macro-transformer
1263 (^[f r c]
1264 (match f
1265 [(_ arg (? pair? specs) . body)
1266 (define (rec arg vars&inits rest)
1267 (cond
1268 [(null? (cdr vars&inits))
1269 (quasirename r
1270 `((let ((,(caar vars&inits)
1271 (if (null? ,arg) ,(cdar vars&inits) (car ,arg)))
1272 ,@(if (null? rest)
1273 '()
1274 `((,rest (if (null? ,arg) '() (cdr ,arg))))))
1275 ,@body)))]
1276 [else
1277 (let ([g (gensym)]
1278 [v (caar vars&inits)]
1279 [i (cdar vars&inits)])
1280 ;; NB: if the compiler were more clever, we could use receive
1281 ;; or apply to make (null? ,arg) test once. For now, testing it
1282 ;; twice is faster.
1283 (quasirename r
1284 `((let ((,v (if (null? ,arg) ,i (car ,arg)))
1285 (,g (if (null? ,arg) '() (cdr ,arg))))
1286 ,@(rec g (cdr vars&inits) rest)))))]))
1287 (let1 g (gensym)
1288 (quasirename r
1289 `(let ((,g ,arg))
1290 ,@(rec g (map* (^s
1291 (cond [(and (pair? s) (pair? (cdr s)) (null? (cddr s)))
1292 (cons (car s) (cadr s))]
1293 [(or (symbol? s) (identifier? s))
1294 (cons s `(,(r'undefined)))]
1295 [else (error "malformed let-optionals* bindings:"
1296 specs)]))
1297 (^_ '()) ; ignore last cdr of dotted list
1298 specs)
1299 (cdr (last-pair specs))))))]
1300 [(_ arg (? identifier? var) . body)
1301 ;; A special case when the optional binding list is (). This may
1302 ;; occur as a result of macro expansion, and it's convenient to
1303 ;; handle it here instead of each macro expander special-case it.
1304 (quasirename r
1305 `(let ((,var ,arg)) ,@body))]
1306 [_ (error "Malformed let-optionals*:" f)]))))
1307
1308 (select-module gauche)
1309 (define-syntax let-keywords
1310 (er-macro-transformer
1311 (^[f r c] ((with-module gauche.internal %let-keywords-rec) f r 'let))))
1312
1313 (define-syntax let-keywords*
1314 (er-macro-transformer
1315 (^[f r c] ((with-module gauche.internal %let-keywords-rec) f r 'let*))))
1316
1317 (select-module gauche.internal)
1318 (use util.match)
1319 (define (%let-keywords-rec form rename %let)
1320 ;; arg is either:
1321 ;; identidfir
1322 ;; (identifier default-expr)
1323 ;; (identifier keyword default-expr)
1324 ;; returns (values identifier keyword default-expr)
1325 (define (triplet var&default)
1326 (or (and-let* ([ (list? var&default) ]
1327 [var (unwrap-syntax (car var&default))]
1328 [ (symbol? var) ])
1329 (case (length var&default)
1330 [(2) (values (car var&default)
1331 (make-keyword var)
1332 (cadr var&default))]
1333 [(3) (values (car var&default)
1334 (unwrap-syntax (cadr var&default))
1335 (caddr var&default))]
1336 [else #f]))
1337 (and-let* ([var (unwrap-syntax var&default)]
1338 [ (symbol? var) ])
1339 (values var (make-keyword var) (undefined)))
1340 (error "bad binding form in let-keywords" var&default)))
1341 ;; Loop over var-specs, returns
1342 ;; (values vars ; list of local variables to bound
1343 ;; keys ; list of keywords to detect
1344 ;; defaults ; list of expressions for the default
1345 ;; tmps ; list of temporary variables
1346 ;; restvar) ; #f, #t or identifier
1347 (define (process-specs specs)
1348 (let loop ((specs specs)
1349 (vars '()) (keys '()) (defaults '()) (tmps '()))
1350 (define (finish restvar)
1351 (values (reverse! vars)
1352 (reverse! keys)
1353 (reverse! defaults)
1354 (reverse! tmps)
1355 restvar))
1356 (cond [(null? specs) (finish #f)]
1357 [(pair? specs)
1358 (receive (var key default) (triplet (car specs))
1359 (loop (cdr specs)
1360 (cons var vars)
1361 (cons key keys)
1362 (cons default defaults)
1363 (cons (gensym) tmps)))]
1364 [else (finish (or specs #t))])))
1365 (match form
1366 [(_ arg specs . body)
1367 (let ([argvar (gensym "args")]
1368 [loop (gensym "loop")]
1369 [let. (rename %let)])
1370 (receive (vars keys defaults tmps restvar) (process-specs specs)
1371 (quasirename rename
1372 `(let
1373 ,loop ((,argvar ,arg)
1374 ,@(if (boolean? restvar) '() `((,restvar '())))
1375 ,@(map (cut list <> (undefined)) tmps))
1376 (cond
1377 [(null? ,argvar)
1378 (,let. ,(map (^[var tmp default]
1379 (quasirename rename
1380 `(,var (if (undefined? ,tmp) ,default ,tmp))))
1381 vars tmps defaults)
1382 ,@body)]
1383 [(null? (cdr ,argvar))
1384 (error "keyword list not even" ,argvar)]
1385 [else
1386 (case (unwrap-syntax-1 (car ,argvar))
1387 ,@(map (^[key]
1388 (quasirename rename
1389 `((,key)
1390 (,loop (cddr ,argvar)
1391 ,@(if (boolean? restvar)
1392 '()
1393 `(,restvar))
1394 ,@(map (^[k t] (if (eq? key k)
1395 (quasirename rename
1396 `(cadr ,argvar))
1397 t))
1398 keys tmps)))))
1399 keys)
1400 (else
1401 ,(cond [(eq? restvar #t)
1402 (quasirename rename
1403 `(,loop (cddr ,argvar) ,@tmps))]
1404 [(eq? restvar #f)
1405 (quasirename rename
1406 `(begin
1407 (errorf "unknown keyword ~S" (car ,argvar))
1408 (,loop (cddr ,argvar) ,@tmps)))]
1409 [else
1410 (quasirename rename
1411 `(,loop
1412 (cddr ,argvar)
1413 (list* (car ,argvar) (cadr ,argvar) ,restvar)
1414 ,@tmps))])))])))))]
1415 [_ (errorf "Malformed ~a: ~S"
1416 (if (eq? %let 'let) 'let-keywords 'let-keywords*)
1417 form)]))
1418
1419 ;;; object system
1420
1421 (select-module gauche)
1422
1423 (define-syntax define-class
1424 (er-macro-transformer
1425 (^[f r c]
1426 (match f
1427 [(_ name supers slots . options)
1428 ($ (with-module gauche.object %expand-define-class)
1429 name supers slots options)]
1430 [_ (error "syntax-error: malformed define-class:" f)]))))
1431
1432 (define-syntax define-generic
1433 (er-macro-transformer
1434 (^[f r c]
1435 (match f
1436 [(_ name . opts)
1437 ((with-module gauche.object %expand-define-generic) name opts)]
1438 [_ (error "syntax-error: malformed define-generic:" f)]))))
1439
1440 (define-syntax define-method
1441 (er-macro-transformer
1442 (^[f r c]
1443 (define (gather-quals name rest quals)
1444 (match rest
1445 [((? keyword? q) . rest)
1446 (gather-quals name rest (cons q quals))]
1447 [(specs . body)
1448 ($ (with-module gauche.object %expand-define-method)
1449 name (reverse quals) specs body f)]
1450 [_ (error "syntax-error: malformed define-method (empty body):" f)]))
1451 (match f
1452 [(_ name . rest) (gather-quals name rest '())]
1453 [_ (error "syntax-error: malformed define-method:" f)]))))
1454
1455 ;;; lseq
1456 (select-module gauche)
1457 (define-syntax lcons
1458 (er-macro-transformer
1459 (^[f r c]
1460 (match f
1461 [(_ x y)
1462 (quasirename r
1463 `(,(with-module gauche.internal %lcons) ,x (lambda () ,y)))]
1464 [(_ x y attrs)
1465 (quasirename r
1466 `(,(with-module gauche.internal %lcons) ,x (lambda () ,y) ,attrs))]))))
1467
1468 (define-syntax lcons*
1469 (er-macro-transformer
1470 (^[f r c]
1471 (match f
1472 [(_ x) x]
1473 [(_ x y) (quasirename r `(lcons ,x ,y))]
1474 [(_ x y z ...) (quasirename r
1475 `(cons ,x (lcons* ,y ,@z)))]))))
1476
1477 (define-syntax llist* lcons*)
1478
1479
1480 ;;; format
1481
1482 (select-module gauche.format)
1483 (use util.match)
1484
1485 (define-syntax make-format-transformer
1486 (er-macro-transformer
1487 (^[f r c]
1488 (match f
1489 [(_ shared?)
1490 (quasirename r
1491 `(er-macro-transformer
1492 (^[f r c]
1493 (define (context-literal pos) `(,',shared? ,pos ,(box #f)))
1494 (match f
1495 [(_ (? string?) . _)
1496 (quasirename r
1497 `(format-internal ',(context-literal 0) (list ,@(cdr f))))]
1498 [(_ _ (? string?) . _)
1499 (quasirename r
1500 `(format-internal ',(context-literal 1) (list ,@(cdr f))))]
1501 [(_ _ _ (? string?) . _)
1502 (quasirename r
1503 `(format-internal ',(context-literal 2) (list ,@(cdr f))))]
1504 [_ f]))))]))))
1505
1506 (define-hybrid-syntax format
1507 (^ args (format-internal '(#f #f #f) args))
1508 (make-format-transformer #f))
1509
1510 (define-hybrid-syntax format/ss
1511 (^ args (format-internal '(#t #f #f) args))
1512 (make-format-transformer #t))
1513
1514 (select-module gauche)
1515 (define-inline format (with-module gauche.format format))
1516 (define-inline format/ss (with-module gauche.format format/ss))
1517
1518 ;;; rxmatch-* macros
1519
1520 (select-module gauche)
1521 ;; rxmatch-let expr (var ...) form ...
1522 (define-syntax rxmatch-let
1523 (er-macro-transformer
1524 (^[f r c]
1525 (match f
1526 [(_ expr (var ...) form ...)
1527 (quasirename r
1528 `(if-let1 m ,expr
1529 (let ,(map (^[v i] (quasirename r
1530 `(,v (rxmatch-substring m ,i))))
1531 var (iota (length var)))
1532 ,@form)
1533 (error "rxmatch-let: match failed:" ',expr)))]
1534 [_ (error "malformed rxmatch-let:" f)]))))
1535
1536 ;; rxmatch-if expr (var ...) then else
1537 (define-syntax rxmatch-if
1538 (er-macro-transformer
1539 (^[f r c]
1540 (match f
1541 [(_ expr (var ...) then else)
1542 (quasirename r
1543 `(if-let1 m ,expr
1544 (let ,(append-map (^[v i]
1545 (if v
1546 (quasirename r
1547 `((,v (rxmatch-substring m ,i))))
1548 '()))
1549 var (iota (length var)))
1550 ,then)
1551 ,else))]
1552 [_ (error "malformed rxmatch-if:" f)]))))
1553
1554 ;; rxmatch-cond (expr bind form ...) ... [(else form ...)]
1555 (define-syntax rxmatch-cond
1556 (er-macro-transformer
1557 (^[f r c]
1558 (define (test.? x) (c (r'test) x))
1559 (define (else.? x) (c (r'else) x))
1560 (define (=>.? x) (c (r'=>) x))
1561 (let loop ([clauses (cdr f)])
1562 (match clauses
1563 [() `(,(r'undefined))]
1564 [(((? else.?) form ...) . rest)
1565 (if (null? rest)
1566 (quasirename r `(begin ,@form))
1567 (error "extra stuff after else clause in rxmatch-cond:" f))]
1568 [(((? test.?) expr (? =>.?) proc) . rest)
1569 (quasirename r
1570 `(if-let1 x ,expr
1571 (,proc x)
1572 ,(loop rest)))]
1573 [(((? test.?) expr form ...) . rest)
1574 (quasirename r
1575 `(if ,expr
1576 (begin ,@form)
1577 ,(loop rest)))]
1578 [((matchexp (var ...) form ...) . rest)
1579 (quasirename r
1580 `(rxmatch-if ,matchexp ,var
1581 (begin ,@form)
1582 ,(loop rest)))]
1583 [_ (error "bad clause in rxmatch-cond:" (car clause))])))))
1584
1585 ;; rxmatch-case exp clause ...
1586 ;; clause: (re bind form ...)
1587 ;; (test pred form ...)
1588 ;; (test pred => proc)
1589 ;; (else form ...)
1590 ;; (else => proc)
1591 (define-syntax rxmatch-case
1592 (er-macro-transformer
1593 (^[f r c]
1594 (define (test.? x) (c (r'test) x))
1595 (define (else.? x) (c (r'else) x))
1596 (define (=>.? x) (c (r'=>) x))
1597 (define tmp. (r'tmp))
1598 (define strp. (r'strp))
1599 (define (loop clauses)
1600 (match clauses
1601 [() `(,(r'undefined))]
1602 [(((? else.?) (? =>.?) proc) . rest)
1603 (if (null? rest)
1604 `(,proc ,tmp.)
1605 (error "extra stuff after else clause in rxmatch-case:" f))]
1606 [(((? else.?) form ...) . rest)
1607 (if (null? rest)
1608 (quasirename r `(begin ,@form))
1609 (error "extra stuff after else clause in rxmatch-case:" f))]
1610 [(((? test.?) pred (? =>.?) proc) . rest)
1611 (quasirename r
1612 `(if-let1 x (,pred ,tmp.)
1613 (,proc x)
1614 ,(loop rest)))]
1615 [(((? test.?) pred form ...) . rest)
1616 (quasirename r
1617 `(if (,pred ,tmp.)
1618 (begin ,@form)
1619 ,(loop rest)))]
1620 [((re (var ...) form ...) . rest)
1621 (quasirename r
1622 `(rxmatch-if (and ,strp. (rxmatch ,re ,tmp.)) ,var
1623 (begin ,@form)
1624 ,(loop rest)))]
1625 [_ (error "bad clause in rxmatch-case:" (car clause))]))
1626 (match f
1627 [(_ exp . clauses)
1628 (quasirename r
1629 `(let* ([,tmp. ,exp]
1630 [,strp. (string? ,tmp.)])
1631 ,(loop clauses)))]
1632 [_ (error "malformed rxmatch-case:" f)]))))
1633
1634
1635 ;;; SRFI-236
1636
1637 (define-syntax independently
1638 (er-macro-transformer
1639 (^[f r c]
1640 (quasirename r
1641 `(let ,(map (^[expr] (quasirename r
1642 `(,(gensym) (begin ,expr #f))))
1643 (cdr f))
1644 (undefined))))))