optargs.scm 16 KB

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