home *** CD-ROM | disk | FTP | other *** search
/ HAKERIS 11 / HAKERIS 11.ISO / linux / system / LinuxConsole 0.4 / linuxconsole0.4install-en.iso / guile0.4.lcm / share / guile / 1.6.0 / ice-9 / optargs.scm < prev    next >
Encoding:
Text File  |  2004-01-06  |  16.5 KB  |  458 lines

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