Merge commit 'e20d7001c3f7150400169fecb0bf0eefdf122fe2' into vm-check
[bpt/guile.git] / module / ice-9 / optargs.scm
1 ;;;; optargs.scm -- support for optional arguments
2 ;;;;
3 ;;;; Copyright (C) 1997, 1998, 1999, 2001, 2002, 2004, 2006 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 2.1 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 ;;;; Contributed by Maciej Stachowiak <mstachow@alum.mit.edu>
20
21 \f
22
23 ;;; Commentary:
24
25 ;;; {Optional Arguments}
26 ;;;
27 ;;; The C interface for creating Guile procedures has a very handy
28 ;;; "optional argument" feature. This module attempts to provide
29 ;;; similar functionality for procedures defined in Scheme with
30 ;;; a convenient and attractive syntax.
31 ;;;
32 ;;; exported macros are:
33 ;;; let-optional
34 ;;; let-optional*
35 ;;; let-keywords
36 ;;; let-keywords*
37 ;;; lambda*
38 ;;; define*
39 ;;; define*-public
40 ;;; defmacro*
41 ;;; defmacro*-public
42 ;;;
43 ;;;
44 ;;; Summary of the lambda* extended parameter list syntax (brackets
45 ;;; are used to indicate grouping only):
46 ;;;
47 ;;; ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
48 ;;; [#:key [ext-var-decl]+ [#:allow-other-keys]?]?
49 ;;; [[#:rest identifier]|[. identifier]]?
50 ;;;
51 ;;; ext-var-decl ::= identifier | ( identifier expression )
52 ;;;
53 ;;; The characters `*', `+' and `?' are not to be taken literally; they
54 ;;; mean respectively, zero or more occurences, one or more occurences,
55 ;;; and one or zero occurences.
56 ;;;
57
58 ;;; Code:
59
60 (define-module (ice-9 optargs)
61 :export-syntax (let-optional
62 let-optional*
63 let-keywords
64 let-keywords*
65 define* lambda*
66 define*-public
67 defmacro*
68 defmacro*-public))
69
70 ;; let-optional rest-arg (binding ...) . body
71 ;; let-optional* rest-arg (binding ...) . body
72 ;; macros used to bind optional arguments
73 ;;
74 ;; These two macros give you an optional argument interface that is
75 ;; very "Schemey" and introduces no fancy syntax. They are compatible
76 ;; with the scsh macros of the same name, but are slightly
77 ;; extended. Each of binding may be of one of the forms <var> or
78 ;; (<var> <default-value>). rest-arg should be the rest-argument of
79 ;; the procedures these are used from. The items in rest-arg are
80 ;; sequentially bound to the variable namess are given. When rest-arg
81 ;; runs out, the remaining vars are bound either to the default values
82 ;; or to `#f' if no default value was specified. rest-arg remains
83 ;; bound to whatever may have been left of rest-arg.
84 ;;
85
86 (defmacro let-optional (REST-ARG BINDINGS . BODY)
87 (let-optional-template REST-ARG BINDINGS BODY 'let))
88
89 (defmacro let-optional* (REST-ARG BINDINGS . BODY)
90 (let-optional-template REST-ARG BINDINGS BODY 'let*))
91
92
93
94 ;; let-keywords rest-arg allow-other-keys? (binding ...) . body
95 ;; let-keywords* rest-arg allow-other-keys? (binding ...) . body
96 ;; macros used to bind keyword arguments
97 ;;
98 ;; These macros pick out keyword arguments from rest-arg, but do not
99 ;; modify it. This is consistent at least with Common Lisp, which
100 ;; duplicates keyword args in the rest arg. More explanation of what
101 ;; keyword arguments in a lambda list look like can be found below in
102 ;; the documentation for lambda*. Bindings can have the same form as
103 ;; for let-optional. If allow-other-keys? is false, an error will be
104 ;; thrown if anything that looks like a keyword argument but does not
105 ;; match a known keyword parameter will result in an error.
106 ;;
107
108
109 (defmacro let-keywords (REST-ARG ALLOW-OTHER-KEYS? BINDINGS . BODY)
110 (let-keywords-template REST-ARG ALLOW-OTHER-KEYS? BINDINGS BODY 'let))
111
112 (defmacro let-keywords* (REST-ARG ALLOW-OTHER-KEYS? BINDINGS . BODY)
113 (let-keywords-template REST-ARG ALLOW-OTHER-KEYS? BINDINGS BODY 'let*))
114
115
116 ;; some utility procedures for implementing the various let-forms.
117
118 (define (let-o-k-template REST-ARG BINDINGS BODY let-type proc)
119 (let ((bindings (map (lambda (x)
120 (if (list? x)
121 x
122 (list x #f)))
123 BINDINGS)))
124 `(,let-type ,(map proc bindings) ,@BODY)))
125
126 (define (let-optional-template REST-ARG BINDINGS BODY let-type)
127 (if (null? BINDINGS)
128 `(let () ,@BODY)
129 (let-o-k-template REST-ARG BINDINGS BODY let-type
130 (lambda (optional)
131 `(,(car optional)
132 (cond
133 ((not (null? ,REST-ARG))
134 (let ((result (car ,REST-ARG)))
135 ,(list 'set! REST-ARG
136 `(cdr ,REST-ARG))
137 result))
138 (else
139 ,(cadr optional))))))))
140
141 (define (let-keywords-template REST-ARG ALLOW-OTHER-KEYS? BINDINGS BODY let-type)
142 (if (null? BINDINGS)
143 `(let () ,@BODY)
144 (let* ((kb-list-gensym (gensym "kb:G"))
145 (bindfilter (lambda (key)
146 `(,(car key)
147 (cond
148 ((assq ',(car key) ,kb-list-gensym)
149 => cdr)
150 (else
151 ,(cadr key)))))))
152 `(let ((,kb-list-gensym ((@@ (ice-9 optargs) rest-arg->keyword-binding-list)
153 ,REST-ARG ',(map (lambda (x) (symbol->keyword (if (pair? x) (car x) x)))
154 BINDINGS)
155 ,ALLOW-OTHER-KEYS?)))
156 ,(let-o-k-template REST-ARG BINDINGS BODY let-type bindfilter)))))
157
158
159 (define (rest-arg->keyword-binding-list rest-arg keywords allow-other-keys?)
160 (if (null? rest-arg)
161 '()
162 (let loop ((first (car rest-arg))
163 (rest (cdr rest-arg))
164 (accum '()))
165 (let ((next (lambda (a)
166 (if (null? (cdr rest))
167 a
168 (loop (cadr rest) (cddr rest) a)))))
169 (if (keyword? first)
170 (cond
171 ((memq first keywords)
172 (if (null? rest)
173 (error "Keyword argument has no value.")
174 (next (cons (cons (keyword->symbol first)
175 (car rest)) accum))))
176 ((not allow-other-keys?)
177 (error "Unknown keyword in arguments."))
178 (else (if (null? rest)
179 accum
180 (next accum))))
181 (if (null? rest)
182 accum
183 (loop (car rest) (cdr rest) accum)))))))
184
185
186 ;; lambda* args . body
187 ;; lambda extended for optional and keyword arguments
188 ;;
189 ;; lambda* creates a procedure that takes optional arguments. These
190 ;; are specified by putting them inside brackets at the end of the
191 ;; paramater list, but before any dotted rest argument. For example,
192 ;; (lambda* (a b #:optional c d . e) '())
193 ;; creates a procedure with fixed arguments a and b, optional arguments c
194 ;; and d, and rest argument e. If the optional arguments are omitted
195 ;; in a call, the variables for them are bound to `#f'.
196 ;;
197 ;; lambda* can also take keyword arguments. For example, a procedure
198 ;; defined like this:
199 ;; (lambda* (#:key xyzzy larch) '())
200 ;; can be called with any of the argument lists (#:xyzzy 11)
201 ;; (#:larch 13) (#:larch 42 #:xyzzy 19) (). Whichever arguments
202 ;; are given as keywords are bound to values.
203 ;;
204 ;; Optional and keyword arguments can also be given default values
205 ;; which they take on when they are not present in a call, by giving a
206 ;; two-item list in place of an optional argument, for example in:
207 ;; (lambda* (foo #:optional (bar 42) #:key (baz 73)) (list foo bar baz))
208 ;; foo is a fixed argument, bar is an optional argument with default
209 ;; value 42, and baz is a keyword argument with default value 73.
210 ;; Default value expressions are not evaluated unless they are needed
211 ;; and until the procedure is called.
212 ;;
213 ;; lambda* now supports two more special parameter list keywords.
214 ;;
215 ;; lambda*-defined procedures now throw an error by default if a
216 ;; keyword other than one of those specified is found in the actual
217 ;; passed arguments. However, specifying #:allow-other-keys
218 ;; immediately after the keyword argument declarations restores the
219 ;; previous behavior of ignoring unknown keywords. lambda* also now
220 ;; guarantees that if the same keyword is passed more than once, the
221 ;; last one passed is the one that takes effect. For example,
222 ;; ((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
223 ;; #:heads 37 #:tails 42 #:heads 99)
224 ;; would result in (99 47) being displayed.
225 ;;
226 ;; #:rest is also now provided as a synonym for the dotted syntax rest
227 ;; argument. The argument lists (a . b) and (a #:rest b) are equivalent in
228 ;; all respects to lambda*. This is provided for more similarity to DSSSL,
229 ;; MIT-Scheme and Kawa among others, as well as for refugees from other
230 ;; Lisp dialects.
231
232
233 (defmacro lambda* (ARGLIST . BODY)
234 (parse-arglist
235 ARGLIST
236 (lambda (non-optional-args optionals keys aok? rest-arg)
237 ;; Check for syntax errors.
238 (if (not (every? symbol? non-optional-args))
239 (error "Syntax error in fixed argument declaration."))
240 (if (not (every? ext-decl? optionals))
241 (error "Syntax error in optional argument declaration."))
242 (if (not (every? ext-decl? keys))
243 (error "Syntax error in keyword argument declaration."))
244 (if (not (or (symbol? rest-arg) (eq? #f rest-arg)))
245 (error "Syntax error in rest argument declaration."))
246 ;; generate the code.
247 (let ((rest-gensym (or rest-arg (gensym "lambda*:G")))
248 (lambda-gensym (gensym "lambda*:L")))
249 (if (not (and (null? optionals) (null? keys)))
250 `(let ((,lambda-gensym
251 (lambda (,@non-optional-args . ,rest-gensym)
252 ;; Make sure that if the proc had a docstring, we put it
253 ;; here where it will be visible.
254 ,@(if (and (not (null? BODY))
255 (string? (car BODY)))
256 (list (car BODY))
257 '())
258 (let-optional*
259 ,rest-gensym
260 ,optionals
261 (let-keywords* ,rest-gensym
262 ,aok?
263 ,keys
264 ,@(if (and (not rest-arg) (null? keys))
265 `((if (not (null? ,rest-gensym))
266 (error "Too many arguments.")))
267 '())
268 (let ()
269 ,@BODY))))))
270 (set-procedure-property! ,lambda-gensym 'arglist
271 '(,non-optional-args
272 ,optionals
273 ,keys
274 ,aok?
275 ,rest-arg))
276 ,lambda-gensym)
277 `(lambda (,@non-optional-args . ,(if rest-arg rest-arg '()))
278 ,@BODY))))))
279
280
281 (define (every? pred lst)
282 (or (null? lst)
283 (and (pred (car lst))
284 (every? pred (cdr lst)))))
285
286 (define (ext-decl? obj)
287 (or (symbol? obj)
288 (and (list? obj) (= 2 (length obj)) (symbol? (car obj)))))
289
290 ;; XXX - not tail recursive
291 (define (improper-list-copy obj)
292 (if (pair? obj)
293 (cons (car obj) (improper-list-copy (cdr obj)))
294 obj))
295
296 (define (parse-arglist arglist cont)
297 (define (split-list-at val lst cont)
298 (cond
299 ((memq val lst)
300 => (lambda (pos)
301 (if (memq val (cdr pos))
302 (error (with-output-to-string
303 (lambda ()
304 (map display `(,val
305 " specified more than once in argument list.")))))
306 (cont (reverse (cdr (memq val (reverse lst)))) (cdr pos) #t))))
307 (else (cont lst '() #f))))
308 (define (parse-opt-and-fixed arglist keys aok? rest cont)
309 (split-list-at
310 #:optional arglist
311 (lambda (before after split?)
312 (if (and split? (null? after))
313 (error "#:optional specified but no optional arguments declared.")
314 (cont before after keys aok? rest)))))
315 (define (parse-keys arglist rest cont)
316 (split-list-at
317 #:allow-other-keys arglist
318 (lambda (aok-before aok-after aok-split?)
319 (if (and aok-split? (not (null? aok-after)))
320 (error "#:allow-other-keys not at end of keyword argument declarations.")
321 (split-list-at
322 #:key aok-before
323 (lambda (key-before key-after key-split?)
324 (cond
325 ((and aok-split? (not key-split?))
326 (error "#:allow-other-keys specified but no keyword arguments declared."))
327 (key-split?
328 (cond
329 ((null? key-after) (error "#:key specified but no keyword arguments declared."))
330 ((memq #:optional key-after) (error "#:optional arguments declared after #:key arguments."))
331 (else (parse-opt-and-fixed key-before key-after aok-split? rest cont))))
332 (else (parse-opt-and-fixed arglist '() #f rest cont)))))))))
333 (define (parse-rest arglist cont)
334 (cond
335 ((null? arglist) (cont '() '() '() #f #f))
336 ((not (pair? arglist)) (cont '() '() '() #f arglist))
337 ((not (list? arglist))
338 (let* ((copy (improper-list-copy arglist))
339 (lp (last-pair copy))
340 (ra (cdr lp)))
341 (set-cdr! lp '())
342 (if (memq #:rest copy)
343 (error "Cannot specify both #:rest and dotted rest argument.")
344 (parse-keys copy ra cont))))
345 (else (split-list-at
346 #:rest arglist
347 (lambda (before after split?)
348 (if split?
349 (case (length after)
350 ((0) (error "#:rest not followed by argument."))
351 ((1) (parse-keys before (car after) cont))
352 (else (error "#:rest argument must be declared last.")))
353 (parse-keys before #f cont)))))))
354
355 (parse-rest arglist cont))
356
357
358
359 ;; define* args . body
360 ;; define*-public args . body
361 ;; define and define-public extended for optional and keyword arguments
362 ;;
363 ;; define* and define*-public support optional arguments with
364 ;; a similar syntax to lambda*. They also support arbitrary-depth
365 ;; currying, just like Guile's define. Some examples:
366 ;; (define* (x y #:optional a (z 3) #:key w . u) (display (list y z u)))
367 ;; defines a procedure x with a fixed argument y, an optional agument
368 ;; a, another optional argument z with default value 3, a keyword argument w,
369 ;; and a rest argument u.
370 ;; (define-public* ((foo #:optional bar) #:optional baz) '())
371 ;; This illustrates currying. A procedure foo is defined, which,
372 ;; when called with an optional argument bar, returns a procedure that
373 ;; takes an optional argument baz.
374 ;;
375 ;; Of course, define*[-public] also supports #:rest and #:allow-other-keys
376 ;; in the same way as lambda*.
377
378 (defmacro define* (ARGLIST . BODY)
379 (define*-guts 'define ARGLIST BODY))
380
381 (defmacro define*-public (ARGLIST . BODY)
382 (define*-guts 'define-public ARGLIST BODY))
383
384 ;; The guts of define* and define*-public.
385 (define (define*-guts DT ARGLIST BODY)
386 (define (nest-lambda*s arglists)
387 (if (null? arglists)
388 BODY
389 `((lambda* ,(car arglists) ,@(nest-lambda*s (cdr arglists))))))
390 (define (define*-guts-helper ARGLIST arglists)
391 (let ((first (car ARGLIST))
392 (al (cons (cdr ARGLIST) arglists)))
393 (if (symbol? first)
394 `(,DT ,first ,@(nest-lambda*s al))
395 (define*-guts-helper first al))))
396 (if (symbol? ARGLIST)
397 `(,DT ,ARGLIST ,@BODY)
398 (define*-guts-helper ARGLIST '())))
399
400
401
402 ;; defmacro* name args . body
403 ;; defmacro*-public args . body
404 ;; defmacro and defmacro-public extended for optional and keyword arguments
405 ;;
406 ;; These are just like defmacro and defmacro-public except that they
407 ;; take lambda*-style extended paramter lists, where #:optional,
408 ;; #:key, #:allow-other-keys and #:rest are allowed with the usual
409 ;; semantics. Here is an example of a macro with an optional argument:
410 ;; (defmacro* transmorgify (a #:optional b)
411
412 (defmacro defmacro* (NAME ARGLIST . BODY)
413 (defmacro*-guts 'define NAME ARGLIST BODY))
414
415 (defmacro defmacro*-public (NAME ARGLIST . BODY)
416 (defmacro*-guts 'define-public NAME ARGLIST BODY))
417
418 ;; The guts of defmacro* and defmacro*-public
419 (define (defmacro*-guts DT NAME ARGLIST BODY)
420 `(,DT ,NAME
421 (,(lambda (transformer) (defmacro:transformer transformer))
422 (lambda* ,ARGLIST ,@BODY))))
423
424 ;;; optargs.scm ends here