home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / utils / cl.el < prev    next >
Encoding:
Text File  |  1992-06-29  |  88.9 KB  |  2,481 lines

  1. ;; Common-Lisp extensions for GNU Emacs Lisp.
  2. ;; Copyright (C) 1987, 1988 Free Software Foundation, Inc.
  3.  
  4. ;; This file is part of GNU Emacs.
  5.  
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation; either version 1, or (at your option)
  9. ;; any later version.
  10.  
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ;; GNU General Public License for more details.
  15.  
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  18. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. ;;;;
  21. ;;;; These are extensions to Emacs Lisp that provide some form of
  22. ;;;; Common Lisp compatibility, beyond what is already built-in
  23. ;;;; in Emacs Lisp.
  24. ;;;;
  25. ;;;; When developing them, I had the code spread among several files.
  26. ;;;; This file 'cl.el' is a concatenation of those original files,
  27. ;;;; minus some declarations that became redundant.  The marks between
  28. ;;;; the original files can be found easily, as they are lines that
  29. ;;;; begin with four semicolons (as this does).  The names of the
  30. ;;;; original parts follow the four semicolons in uppercase, those
  31. ;;;; names are GLOBAL, SYMBOLS, LISTS, SEQUENCES, CONDITIONALS,
  32. ;;;; ITERATIONS, MULTIPLE VALUES, ARITH, SETF and DEFSTRUCT.  If you
  33. ;;;; add functions to this file, you might want to put them in a place
  34. ;;;; that is compatible with the division above (or invent your own
  35. ;;;; categories).
  36. ;;;;
  37. ;;;; To compile this file, make sure you load it first.  This is
  38. ;;;; because many things are implemented as macros and now that all
  39. ;;;; the files are concatenated together one cannot ensure that
  40. ;;;; declaration always precedes use.
  41. ;;;;
  42. ;;;; Bug reports, suggestions and comments,
  43. ;;;; to quiroz@cs.rochester.edu
  44.  
  45. (provide 'cl)
  46.  
  47. ;; Cause the byte-compiler to load this library
  48. ;; when trying to compile it.
  49. (require 'cl)
  50.  
  51. ;;;; GLOBAL
  52. ;;;;    This file provides utilities and declarations that are global
  53. ;;;;    to Common Lisp and so might be used by more than one of the
  54. ;;;;    other libraries.  Especially, I intend to keep here some
  55. ;;;;    utilities that help parsing/destructuring some difficult calls. 
  56. ;;;;
  57. ;;;;
  58. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  59. ;;;;       (quiroz@cs.rochester.edu)
  60.  
  61. (defmacro psetq (&rest pairs)
  62.   "(psetq {VARIABLE VALUE}...): In parallel, set each VARIABLE to its VALUE.
  63. All the VALUEs are evaluated, and then all the VARIABLEs are set.
  64. Aside from order of evaluation, this is the same as `setq'."
  65.   (let ((nforms (length pairs))        ;count of args
  66.     ;; next are used to destructure the call
  67.     symbols                ;even numbered args
  68.     forms                ;odd numbered args
  69.     ;; these are used to generate code
  70.     bindings            ;for the let
  71.     newsyms                ;list of gensyms
  72.     assignments            ;for the setq
  73.     ;; auxiliary indices
  74.     i)
  75.     ;; check there is a reasonable number of forms
  76.     (if (/= (% nforms 2) 0)
  77.     (error "Odd number of arguments to `psetq'"))
  78.  
  79.     ;; destructure the args
  80.     (let ((ptr pairs)            ;traverses the args
  81.       var                ;visits each symbol position
  82.       )
  83.       (while ptr
  84.     (setq var (car ptr))        ;next variable
  85.     (if (not (symbolp var))
  86.         (error "`psetq' expected a symbol, found '%s'."
  87.            (prin1-to-string var)))
  88.     (setq symbols (cons var symbols))
  89.     (setq forms   (cons (car (cdr ptr)) forms))
  90.     (setq ptr (cdr (cdr ptr)))))
  91.  
  92.     ;; assign new symbols to the bindings
  93.     (let ((ptr forms)            ;traverses the forms
  94.       form                ;each form goes here
  95.       newsym            ;gensym for current value of form
  96.       )
  97.       (while ptr
  98.     (setq form (car ptr))
  99.     (setq newsym (gensym))
  100.     (setq bindings (cons (list newsym form) bindings))
  101.     (setq newsyms (cons newsym newsyms))
  102.     (setq ptr (cdr ptr))))
  103.     (setq newsyms (nreverse newsyms))    ;to sync with symbols
  104.     
  105.     ;; pair symbols with newsyms for assignment
  106.     (let ((ptr1 symbols)        ;traverses original names
  107.       (ptr2 newsyms)        ;traverses new symbols
  108.       )
  109.       (while ptr1
  110.     (setq assignments
  111.           (cons (car ptr1) (cons (car ptr2) assignments)))
  112.     (setq ptr1 (cdr ptr1))
  113.     (setq ptr2 (cdr ptr2))))
  114.     
  115.     ;; generate code
  116.     (list 'let
  117.       bindings
  118.       (cons 'setq assignments)
  119.       nil)))
  120.  
  121. ;;; utilities
  122. ;;;
  123. ;;; pair-with-newsyms takes a list and returns a list of lists of the
  124. ;;; form (newsym form), such that a let* can then bind the evaluation
  125. ;;; of the forms to the newsyms.  The idea is to guarantee correct
  126. ;;; order of evaluation of the subforms of a setf.  It also returns a
  127. ;;; list of the newsyms generated, in the corresponding order.
  128.  
  129. (defun pair-with-newsyms (oldforms)
  130.   "PAIR-WITH-NEWSYMS OLDFORMS
  131. The top-level components of the list oldforms are paired with fresh
  132. symbols, the pairings list and the newsyms list are returned."
  133.   (do ((ptr oldforms (cdr ptr))
  134.        (bindings '())
  135.        (newsyms  '()))
  136.       ((endp ptr) (values (nreverse bindings) (nreverse newsyms)))
  137.     (let ((newsym (gentemp)))
  138.       (setq bindings (cons (list newsym (car ptr)) bindings))
  139.       (setq newsyms  (cons newsym newsyms)))))
  140.  
  141. (defun zip-lists (evens odds)
  142.   "Merge two lists EVENS and ODDS, taking elts from each list alternatingly.
  143. EVENS and ODDS are two lists.  ZIP-LISTS constructs a new list, whose
  144. even numbered elements (0,2,...) come from EVENS and whose odd
  145. numbered elements (1,3,...) come from ODDS. 
  146. The construction stops when the shorter list is exhausted."
  147.   (do* ((p0   evens    (cdr p0))
  148.         (p1   odds     (cdr p1))
  149.         (even (car p0) (car p0))
  150.         (odd  (car p1) (car p1))
  151.         (result '()))
  152.       ((or (endp p0) (endp p1))
  153.        (nreverse result))
  154.     (setq result
  155.           (cons odd (cons even result)))))
  156.  
  157. (defun unzip-list (list)
  158.   "Extract even and odd elements of LIST into two separate lists.
  159. The argument LIST is separated in two strands, the even and the odd
  160. numbered elements.  Numbering starts with 0, so the first element
  161. belongs in EVENS. No check is made that there is an even number of
  162. elements to start with."
  163.   (do* ((ptr   list       (cddr ptr))
  164.         (this  (car ptr)  (car ptr))
  165.         (next  (cadr ptr) (cadr ptr))
  166.         (evens '())
  167.         (odds  '()))
  168.       ((endp ptr)
  169.        (values (nreverse evens) (nreverse odds)))
  170.     (setq evens (cons this evens))
  171.     (setq odds  (cons next odds))))
  172.  
  173. (defun reassemble-argslists (argslists)
  174.   "(reassemble-argslists ARGSLISTS).
  175. ARGSLISTS is a list of sequences.  Return a list of lists, the first
  176. sublist being all the entries coming from ELT 0 of the original
  177. sublists, the next those coming from ELT 1 and so on, until the
  178. shortest list is exhausted."
  179.   (let* ((minlen   (apply 'min (mapcar 'length argslists)))
  180.          (result   '()))
  181.     (dotimes (i minlen (nreverse result))
  182.       ;; capture all the elements at index i
  183.       (setq result
  184.             (cons (mapcar
  185.                    (function (lambda (sublist) (elt sublist i)))
  186.                    argslists)
  187.                   result)))))
  188.  
  189. ;;; to help parsing keyword arguments
  190.  
  191. (defun build-klist (argslist acceptable)
  192.   "Decode a keyword argument list ARGSLIST for keywords in ACCEPTABLE.
  193. ARGSLIST is a list, presumably the &rest argument of a call, whose
  194. even numbered elements must be keywords.
  195. ACCEPTABLE is a list of keywords, the only ones that are truly acceptable.
  196. The result is an alist containing the arguments named by the keywords
  197. in ACCEPTABLE, or nil if something failed."
  198.  
  199.   ;; check legality of the arguments, then destructure them
  200.   (unless (and (listp argslist)
  201.                (evenp (length argslist)))
  202.     (error "Odd number of keyword-args"))
  203.   (unless (and (listp acceptable)
  204.                (every 'keywordp acceptable))
  205.     (error "Second arg should be a list of keywords"))
  206.   (multiple-value-bind
  207.       (keywords forms)
  208.       (unzip-list argslist)
  209.     (unless (every 'keywordp keywords)
  210.       (error "Expected keywords, found `%s'"
  211.              (prin1-to-string keywords)))
  212.     (do*                                ;pick up the pieces
  213.         ((auxlist                       ;auxiliary a-list, may
  214.           (pairlis keywords forms))     ;contain repetitions and junk
  215.          (ptr    acceptable  (cdr ptr)) ;pointer in acceptable
  216.          (this  (car ptr)  (car ptr))   ;current acceptable keyword
  217.          (auxval nil)                   ;used to move values around
  218.          (alist  '()))                  ;used to build the result
  219.         ((endp ptr) alist)
  220.       ;; if THIS appears in auxlist, use its value
  221.       (when (setq auxval (assoc this auxlist))
  222.         (setq alist (cons auxval alist))))))
  223.  
  224.  
  225. ;;; Checking that a list of symbols contains no duplicates is a common
  226. ;;; task when checking the legality of some macros.  The check for 'eq
  227. ;;; pairs can be too expensive, as it is quadratic on the length of
  228. ;;; the list.  I use a 4-pass, linear, counting approach.  It surely
  229. ;;; loses on small lists (less than 5 elements?), but should win for
  230. ;;; larger lists.  The fourth pass could be eliminated.
  231. ;;; 10 dec 1986.  Emacs Lisp has no REMPROP, so I just eliminated the
  232. ;;; 4th pass.
  233. (defun duplicate-symbols-p (list)
  234.   "Find all symbols appearing more than once in LIST.
  235. Return a list of all such duplicates; `nil' if there are no duplicates."
  236.   (let  ((duplicates '())               ;result built here
  237.          (propname   (gensym))          ;we use a fresh property
  238.          )
  239.     ;; check validity
  240.     (unless (and (listp list)
  241.                  (every 'symbolp list))
  242.       (error "A list of symbols is needed"))
  243.     ;; pass 1: mark
  244.     (dolist (x list)
  245.       (put x propname 0))
  246.     ;; pass 2: count
  247.     (dolist (x list)
  248.       (put x propname (1+ (get x propname))))
  249.     ;; pass 3: collect
  250.     (dolist (x list)
  251.       (if (> (get x propname) 1)
  252.           (setq duplicates (cons x duplicates))))
  253.     ;; pass 4: unmark.  eliminated.
  254.     ;; (dolist (x list) (remprop x propname))
  255.     ;; return result
  256.     duplicates))
  257.  
  258. ;;;; end of cl-global.el
  259.  
  260. ;;;; SYMBOLS
  261. ;;;;    This file provides the gentemp function, which generates fresh
  262. ;;;;    symbols, plus some other minor Common Lisp symbol tools.
  263. ;;;;
  264. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  265. ;;;;       (quiroz@cs.rochester.edu)
  266.  
  267. ;;; Keywords.  There are no packages in Emacs Lisp, so this is only a
  268. ;;; kludge around to let things be "as if" a keyword package was around.
  269.  
  270. (defmacro defkeyword (x &optional docstring)
  271.   "Make symbol X a keyword (symbol whose value is itself).
  272. Optional second argument is a documentation string for it."
  273.   (cond
  274.    ((symbolp x)
  275.     (list 'defconst x (list 'quote x)))
  276.    (t
  277.     (error "`%s' is not a symbol" (prin1-to-string x)))))
  278.  
  279. (defun keywordp (sym)
  280.   "Return `t' if SYM is a keyword."
  281.   (cond
  282.    ((and (symbolp sym)
  283.          (char-equal (aref (symbol-name sym) 0) ?\:))
  284.     ;; looks like one, make sure value is right
  285.     (set sym sym))
  286.    (t
  287.     nil)))
  288.  
  289. (defun keyword-of (sym)
  290.   "Return a keyword that is naturally associated with symbol SYM.
  291. If SYM is keyword, the value is SYM.
  292. Otherwise it is a keyword whose name is `:' followed by SYM's name."
  293.   (cond
  294.    ((keywordp sym)
  295.     sym)
  296.    ((symbolp sym)
  297.     (let ((newsym (intern (concat ":" (symbol-name sym)))))
  298.       (set newsym newsym)))
  299.    (t
  300.     (error "Expected a symbol, not `%s'" (prin1-to-string sym)))))
  301.  
  302. ;;; Temporary symbols.  
  303. ;;; 
  304.  
  305. (defvar *gentemp-index* 0
  306.   "Integer used by gentemp to produce new names.")
  307.  
  308. (defvar *gentemp-prefix* "T$$_"
  309.   "Names generated by gentemp begin with this string by default.")
  310.  
  311. (defun gentemp (&optional prefix oblist)
  312.   "Generate a fresh interned symbol.
  313. There are 2 optional arguments, PREFIX and OBLIST.  PREFIX is the
  314. string that begins the new name, OBLIST is the obarray used to search for
  315. old names.  The defaults are just right, YOU SHOULD NEVER NEED THESE
  316. ARGUMENTS IN YOUR OWN CODE."
  317.   (if (null prefix)
  318.       (setq prefix *gentemp-prefix*))
  319.   (if (null oblist)
  320.       (setq oblist obarray))            ;default for the intern functions
  321.   (let ((newsymbol nil)
  322.         (newname))
  323.     (while (not newsymbol)
  324.       (setq newname (concat prefix *gentemp-index*))
  325.       (setq *gentemp-index* (+ *gentemp-index* 1))
  326.       (if (not (intern-soft newname oblist))
  327.           (setq newsymbol (intern newname oblist))))
  328.     newsymbol))
  329.  
  330. (defvar *gensym-index* 0
  331.   "Integer used by gensym to produce new names.")
  332.  
  333. (defvar *gensym-prefix* "G$$_"
  334.   "Names generated by gensym begin with this string by default.")
  335.  
  336. (defun gensym (&optional prefix)
  337.   "Generate a fresh uninterned symbol.
  338. There is an  optional argument, PREFIX.  PREFIX is the
  339. string that begins the new name. Most people take just the default,
  340. except when debugging needs suggest otherwise."
  341.   (if (null prefix)
  342.       (setq prefix *gensym-prefix*))
  343.   (let ((newsymbol nil)
  344.         (newname   ""))
  345.     (while (not newsymbol)
  346.       (setq newname (concat prefix *gensym-index*))
  347.       (setq *gensym-index* (+ *gensym-index* 1))
  348.       (if (not (intern-soft newname))
  349.           (setq newsymbol (make-symbol newname))))
  350.     newsymbol))
  351.  
  352. ;;;; end of cl-symbols.el
  353.  
  354. ;;;; CONDITIONALS
  355. ;;;;    This file provides some of the conditional constructs of
  356. ;;;;    Common Lisp.  Total compatibility is again impossible, as the
  357. ;;;;    'if' form is different in both languages, so only a good
  358. ;;;;    approximation is desired.
  359. ;;;;
  360. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  361. ;;;;       (quiroz@cs.rochester.edu)
  362.  
  363. ;;; indentation info
  364. (put 'case      'lisp-indent-function 1)
  365. (put 'ecase     'lisp-indent-function 1)
  366. (put 'when      'lisp-indent-function 1)
  367. (put 'unless    'lisp-indent-function 1)
  368.  
  369. ;;; WHEN and UNLESS
  370. ;;; These two forms are simplified ifs, with a single branch.
  371.  
  372. (defmacro when (condition &rest body)
  373.   "(when CONDITION . BODY) => evaluate BODY if CONDITION is true."
  374.   (list* 'if (list 'not condition) '() body))
  375.  
  376. (defmacro unless (condition &rest body)
  377.   "(unless CONDITION . BODY) => evaluate BODY if CONDITION is false."
  378.   (list* 'if condition '() body))
  379.  
  380. ;;; CASE and ECASE
  381. ;;; CASE selects among several clauses, based on the value (evaluated)
  382. ;;; of a expression and a list of (unevaluated) key values.  ECASE is
  383. ;;; the same, but signals an error if no clause is activated.
  384.  
  385. (defmacro case (expr &rest cases)
  386.   "(case EXPR . CASES) => evals EXPR, chooses from CASES on that value.
  387. EXPR   -> any form
  388. CASES  -> list of clauses, non empty
  389. CLAUSE -> HEAD . BODY
  390. HEAD   -> t             = catch all, must be last clause
  391.        -> otherwise     = same as t
  392.        -> nil           = illegal
  393.        -> atom          = activated if (eql  EXPR HEAD)
  394.        -> list of atoms = activated if (member EXPR HEAD)
  395. BODY   -> list of forms, implicit PROGN is built around it.
  396. EXPR is evaluated only once."
  397.   (let* ((newsym (gentemp))
  398.          (clauses (case-clausify cases newsym)))
  399.     ;; convert case into a cond inside a let
  400.     (list 'let
  401.          (list (list newsym expr))
  402.          (list* 'cond (nreverse clauses)))))
  403.  
  404. (defmacro ecase (expr &rest cases)
  405.   "(ecase EXPR . CASES) => like `case', but error if no case fits.
  406. `t'-clauses are not allowed."
  407.   (let* ((newsym (gentemp))
  408.          (clauses (case-clausify cases newsym)))
  409.     ;; check that no 't clause is present.
  410.     ;; case-clausify would put one such at the beginning of clauses
  411.     (if (eq (caar clauses) t)
  412.         (error "No clause-head should be `t' or `otherwise' for `ecase'"))
  413.     ;; insert error-catching clause
  414.     (setq clauses
  415.           (cons
  416.            (list 't (list 'error
  417.                           "ecase on %s = %s failed to take any branch."
  418.                           (list 'quote expr)
  419.                           (list 'prin1-to-string newsym)))
  420.            clauses))
  421.     ;; generate code as usual
  422.     (list 'let
  423.           (list (list newsym expr))
  424.           (list* 'cond (nreverse clauses)))))
  425.  
  426.  
  427. (defun case-clausify (cases newsym)
  428.   "CASE-CLAUSIFY CASES NEWSYM => clauses for a 'cond'
  429. Converts the CASES of a [e]case macro into cond clauses to be
  430. evaluated inside a let that binds NEWSYM.  Returns the clauses in
  431. reverse order."
  432.   (do* ((currentpos cases        (cdr currentpos))
  433.         (nextpos    (cdr cases)  (cdr nextpos))
  434.         (curclause  (car cases)  (car currentpos))
  435.         (result     '()))
  436.       ((endp currentpos) result)
  437.     (let ((head (car curclause))
  438.           (body (cdr curclause)))
  439.       ;; construct a cond-clause according to the head
  440.       (cond
  441.        ((null head)
  442.         (error "Case clauses cannot have null heads: `%s'"
  443.                (prin1-to-string curclause)))
  444.        ((or (eq head 't)
  445.             (eq head 'otherwise))
  446.         ;; check it is the last clause
  447.         (if (not (endp nextpos))
  448.             (error "Clause with `t' or `otherwise' head must be last"))
  449.         ;; accept this clause as a 't' for cond
  450.         (setq result (cons (cons 't body) result)))
  451.        ((atom head)
  452.         (setq result
  453.               (cons (cons (list 'eql newsym (list 'quote head)) body)
  454.                     result)))
  455.        ((listp head)
  456.         (setq result
  457.               (cons (cons (list 'cl-member newsym (list 'quote head)) body)
  458.                     result)))
  459.        (t
  460.         ;; catch-all for this parser
  461.         (error "Don't know how to parse case clause `%s'."
  462.                (prin1-to-string head)))))))
  463.  
  464. ;;;; end of cl-conditionals.el
  465.  
  466. ;;;; ITERATIONS
  467. ;;;;    This file provides simple iterative macros (a la Common Lisp)
  468. ;;;;    constructed on the basis of let, let* and while, which are the
  469. ;;;;    primitive binding/iteration constructs of Emacs Lisp
  470. ;;;;
  471. ;;;;    The Common Lisp iterations use to have a block named nil
  472. ;;;;    wrapped around them, and allow declarations at the beginning
  473. ;;;;    of their bodies and you can return a value using (return ...).
  474. ;;;;    Nothing of the sort exists in Emacs Lisp, so I haven't tried
  475. ;;;;    to imitate these behaviors.
  476. ;;;;
  477. ;;;;    Other than the above, the semantics of Common Lisp are
  478. ;;;;    correctly reproduced to the extent this was reasonable.
  479. ;;;;
  480. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  481. ;;;;       (quiroz@cs.rochester.edu)
  482.  
  483. ;;; some lisp-indentation information
  484. (put 'do                'lisp-indent-function 2)
  485. (put 'do*               'lisp-indent-function 2)
  486. (put 'dolist            'lisp-indent-function 1)
  487. (put 'dotimes           'lisp-indent-function 1)
  488. (put 'do-symbols        'lisp-indent-function 1)
  489. (put 'do-all-symbols    'lisp-indent-function 1)
  490.  
  491.  
  492. (defmacro do (stepforms endforms &rest body)
  493.   "(do STEPFORMS ENDFORMS . BODY): Iterate BODY, stepping some local variables.
  494. STEPFORMS must be a list of symbols or lists.  In the second case, the
  495. lists must start with a symbol and contain up to two more forms. In
  496. the STEPFORMS, a symbol is the same as a (symbol).  The other 2 forms
  497. are the initial value (def. NIL) and the form to step (def. itself).
  498. The values used by initialization and stepping are computed in parallel.
  499. The ENDFORMS are a list (CONDITION . ENDBODY).  If the CONDITION
  500. evaluates to true in any iteration, ENDBODY is evaluated and the last
  501. form in it is returned.
  502. The BODY (which may be empty) is evaluated at every iteration, with
  503. the symbols of the STEPFORMS bound to the initial or stepped values."
  504.   ;; check the syntax of the macro
  505.   (and (check-do-stepforms stepforms)
  506.        (check-do-endforms endforms))
  507.   ;; construct emacs-lisp equivalent
  508.   (let ((initlist (extract-do-inits stepforms))
  509.         (steplist (extract-do-steps stepforms))
  510.         (endcond  (car endforms))
  511.         (endbody  (cdr endforms)))
  512.     (cons 'let (cons initlist
  513.                      (cons (cons 'while (cons (list 'not endcond) 
  514.                                               (append body steplist)))
  515.                            (append endbody))))))
  516.  
  517.  
  518. (defmacro do* (stepforms endforms &rest body)
  519.   "`do*' is to `do' as `let*' is to `let'.
  520. STEPFORMS must be a list of symbols or lists.  In the second case, the
  521. lists must start with a symbol and contain up to two more forms. In
  522. the STEPFORMS, a symbol is the same as a (symbol).  The other 2 forms
  523. are the initial value (def. NIL) and the form to step (def. itself).
  524. Initializations and steppings are done in the sequence they are written.
  525. The ENDFORMS are a list (CONDITION . ENDBODY).  If the CONDITION
  526. evaluates to true in any iteration, ENDBODY is evaluated and the last
  527. form in it is returned.
  528. The BODY (which may be empty) is evaluated at every iteration, with
  529. the symbols of the STEPFORMS bound to the initial or stepped values."
  530.   ;; check the syntax of the macro
  531.   (and (check-do-stepforms stepforms)
  532.        (check-do-endforms endforms))
  533.   ;; construct emacs-lisp equivalent
  534.   (let ((initlist (extract-do-inits stepforms))
  535.         (steplist (extract-do*-steps stepforms))
  536.         (endcond  (car endforms))
  537.         (endbody  (cdr endforms)))
  538.     (cons 'let* (cons initlist
  539.                      (cons (cons 'while (cons (list 'not endcond) 
  540.                                               (append body steplist)))
  541.                            (append endbody))))))
  542.  
  543.  
  544. ;;; DO and DO* share the syntax checking functions that follow.
  545.  
  546. (defun check-do-stepforms (forms)
  547.   "True if FORMS is a valid stepforms for the do[*] macro (q.v.)"
  548.   (cond
  549.    ((nlistp forms)
  550.     (error "Init/Step form for do[*] should be a list, not `%s'"
  551.            (prin1-to-string forms)))
  552.    (t                                   ;valid list
  553.     ;; each entry must be a symbol, or a list whose car is a symbol
  554.     ;; and whose length is no more than three
  555.     (mapcar
  556.      (function
  557.       (lambda (entry)
  558.         (cond
  559.          ((or (symbolp entry)
  560.               (and (listp entry)
  561.                    (symbolp (car entry))
  562.                    (< (length entry) 4)))
  563.           t)
  564.          (t
  565.           (error
  566.            "Init/Step must be symbol or (symbol [init [step]]), not `%s'"
  567.            (prin1-to-string entry))))))
  568.      forms))))
  569.  
  570. (defun check-do-endforms (forms)
  571.   "True if FORMS is a valid endforms for the do[*] macro (q.v.)"
  572.   (cond
  573.    ((listp forms)
  574.     t)
  575.    (t
  576.     (error "Termination form for do macro should be a list, not `%s'"
  577.            (prin1-to-string forms)))))
  578.  
  579. (defun extract-do-inits (forms)
  580.   "Returns a list of the initializations (for do) in FORMS
  581. -a stepforms, see the do macro-. Forms is assumed syntactically valid."
  582.   (mapcar
  583.    (function
  584.     (lambda (entry)
  585.       (cond
  586.        ((symbolp entry)
  587.         (list entry nil))
  588.        ((listp entry)
  589.         (list (car entry) (cadr entry))))))
  590.    forms))
  591.  
  592. ;;; There used to be a reason to deal with DO differently than with
  593. ;;; DO*.  The writing of PSETQ has made it largely unnecessary.
  594.  
  595. (defun extract-do-steps (forms)
  596.   "EXTRACT-DO-STEPS FORMS => an s-expr
  597. FORMS is the stepforms part of a DO macro (q.v.).  This function
  598. constructs an s-expression that does the stepping at the end of an
  599. iteration."
  600.   (list (cons 'psetq (select-stepping-forms forms))))
  601.  
  602. (defun extract-do*-steps (forms)
  603.   "EXTRACT-DO*-STEPS FORMS => an s-expr
  604. FORMS is the stepforms part of a DO* macro (q.v.).  This function
  605. constructs an s-expression that does the stepping at the end of an
  606. iteration."
  607.   (list (cons 'setq (select-stepping-forms forms))))
  608.  
  609. (defun select-stepping-forms (forms)
  610.   "Separate only the forms that cause stepping."
  611.   (let ((result '())            ;ends up being (... var form ...)
  612.     (ptr forms)            ;to traverse the forms
  613.     entry                ;to explore each form in turn
  614.     )
  615.     (while ptr                ;(not (endp entry)) might be safer
  616.       (setq entry (car ptr))
  617.       (cond
  618.        ((and (listp entry)
  619.          (= (length entry) 3))
  620.     (setq result (append        ;append in reverse order!
  621.               (list (caddr entry) (car entry))
  622.               result))))
  623.       (setq ptr (cdr ptr)))        ;step in the list of forms
  624.     ;;put things back in the
  625.     ;;correct order before return
  626.     (nreverse result)))
  627.  
  628. ;;; Other iterative constructs
  629.  
  630. (defmacro dolist  (stepform &rest body)
  631.   "(dolist (VAR LIST [RESULTFORM]) . BODY): do BODY for each elt of LIST.
  632. The RESULTFORM defaults to nil.  The VAR is bound to successive
  633. elements of the value of LIST and remains bound (to the nil value) when the
  634. RESULTFORM is evaluated."
  635.   ;; check sanity
  636.   (cond
  637.    ((nlistp stepform)
  638.     (error "Stepform for `dolist' should be (VAR LIST [RESULT]), not `%s'"
  639.            (prin1-to-string stepform)))
  640.    ((not (symbolp (car stepform)))
  641.     (error "First component of stepform should be a symbol, not `%s'"
  642.            (prin1-to-string (car stepform))))
  643.    ((> (length stepform) 3)
  644.     (error "Too many components in stepform `%s'"
  645.            (prin1-to-string stepform))))
  646.   ;; generate code
  647.   (let* ((var (car stepform))
  648.          (listform (cadr stepform))
  649.          (resultform (caddr stepform)))
  650.     (list 'progn
  651.           (list 'mapcar
  652.                 (list 'function
  653.                       (cons 'lambda (cons (list var) body)))
  654.                 listform)
  655.           (list 'let
  656.                 (list (list var nil))
  657.                 resultform))))
  658.  
  659. (defmacro dotimes (stepform &rest body)
  660.   "(dotimes (VAR COUNTFORM [RESULTFORM]) .  BODY): Repeat BODY, counting in VAR.
  661. The COUNTFORM should return a positive integer.  The VAR is bound to
  662. successive integers from 0 to COUNTFORM-1 and the BODY is repeated for
  663. each of them.  At the end, the RESULTFORM is evaluated and its value
  664. returned. During this last evaluation, the VAR is still bound, and its
  665. value is the number of times the iteration occurred. An omitted RESULTFORM
  666. defaults to nil."
  667.   ;; check sanity 
  668.   (cond
  669.    ((nlistp stepform)
  670.     (error "Stepform for `dotimes' should be (VAR COUNT [RESULT]), not `%s'"
  671.            (prin1-to-string stepform)))
  672.    ((not (symbolp (car stepform)))
  673.     (error "First component of stepform should be a symbol, not `%s'"
  674.            (prin1-to-string (car stepform))))
  675.    ((> (length stepform) 3)
  676.     (error "Too many components in stepform `%s'"
  677.            (prin1-to-string stepform))))
  678.   ;; generate code
  679.   (let* ((var (car stepform))
  680.          (countform (cadr stepform))
  681.          (resultform (caddr stepform))
  682.          (newsym (gentemp)))
  683.     (list
  684.      'let* (list (list newsym countform))
  685.      (list*
  686.       'do*
  687.       (list (list var 0 (list '+ var 1)))
  688.       (list (list '>= var newsym) resultform)
  689.       body))))
  690.  
  691. (defmacro do-symbols (stepform &rest body)
  692.   "(do_symbols (VAR [OBARRAY [RESULTFORM]]) . BODY)
  693. The VAR is bound to each of the symbols in OBARRAY (def. obarray) and
  694. the BODY is repeatedly performed for each of those bindings. At the
  695. end, RESULTFORM (def. nil) is evaluated and its value returned.
  696. During this last evaluation, the VAR is still bound and its value is nil.
  697. See also the function `mapatoms'."
  698.   ;; check sanity
  699.   (cond
  700.    ((nlistp stepform)
  701.     (error "Stepform for `do-symbols' should be (VAR OBARRAY [RESULT]), not `%s'"
  702.            (prin1-to-string stepform)))
  703.    ((not (symbolp (car stepform)))
  704.     (error "First component of stepform should be a symbol, not `%s'"
  705.            (prin1-to-string (car stepform))))
  706.    ((> (length stepform) 3)
  707.     (error "Too many components in stepform `%s'"
  708.            (prin1-to-string stepform))))
  709.   ;; generate code
  710.   (let* ((var (car stepform))
  711.          (oblist (cadr stepform))
  712.          (resultform (caddr stepform)))
  713.     (list 'progn
  714.           (list 'mapatoms
  715.                 (list 'function
  716.                       (cons 'lambda (cons (list var) body)))
  717.                 oblist)
  718.           (list 'let
  719.                 (list (list var nil))
  720.                 resultform))))
  721.  
  722.  
  723. (defmacro do-all-symbols (stepform &rest body)
  724.   "(do-all-symbols (VAR [RESULTFORM]) . BODY)
  725. Is the same as (do-symbols (VAR obarray RESULTFORM) . BODY)."
  726.   (list*
  727.    'do-symbols
  728.    (list (car stepform) 'obarray (cadr stepform))
  729.    body))
  730.  
  731. (defmacro loop (&rest body)
  732.   "(loop . BODY) repeats BODY indefinitely and does not return.
  733. Normally BODY uses `throw' or `signal' to cause an exit.
  734. The forms in BODY should be lists, as non-lists are reserved for new features."
  735.   ;; check that the body doesn't have atomic forms
  736.   (if (nlistp body)
  737.       (error "Body of `loop' should be a list of lists or nil")
  738.     ;; ok, it is a list, check for atomic components
  739.     (mapcar
  740.      (function (lambda (component)
  741.                  (if (nlistp component)
  742.                      (error "Components of `loop' should be lists"))))
  743.      body)
  744.     ;; build the infinite loop
  745.     (cons 'while (cons 't body))))
  746.  
  747. ;;;; end of cl-iterations.el
  748.  
  749. ;;;; LISTS
  750. ;;;;    This file provides some of the lists machinery of Common-Lisp
  751. ;;;;    in a way compatible with Emacs Lisp.  Especially, see the the
  752. ;;;;    typical c[ad]*r functions.
  753. ;;;;
  754. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  755. ;;;;       (quiroz@cs.rochester.edu)
  756.  
  757.  
  758.  
  759. ;;; Synonyms for list functions
  760. (defun first (x)
  761.   "Synonym for `car'"
  762.   (car x))
  763.  
  764. (defun second (x)
  765.   "Return the second element of the list LIST."
  766.   (nth 1 x))
  767.  
  768. (defun third (x)
  769.   "Return the third element of the list LIST."
  770.   (nth 2 x))
  771.  
  772. (defun fourth (x)
  773.   "Return the fourth element of the list LIST."
  774.   (nth 3 x))
  775.  
  776. (defun fifth (x)
  777.   "Return the fifth element of the list LIST."
  778.   (nth 4 x))
  779.  
  780. (defun sixth (x)
  781.   "Return the sixth element of the list LIST."
  782.   (nth 5 x))
  783.  
  784. (defun seventh (x)
  785.   "Return the seventh element of the list LIST."
  786.   (nth 6 x))
  787.  
  788. (defun eighth (x)
  789.   "Return the eighth element of the list LIST."
  790.   (nth 7 x))
  791.  
  792. (defun ninth (x)
  793.   "Return the ninth element of the list LIST."
  794.   (nth 8 x))
  795.  
  796. (defun tenth (x)
  797.   "Return the tenth element of the list LIST."
  798.   (nth 9 x))
  799.  
  800. (defun rest (x)
  801.   "Synonym for `cdr'"
  802.   (cdr x))
  803.  
  804. (defun endp (x)
  805.   "t if X is nil, nil if X is a cons; error otherwise."
  806.   (if (listp x)
  807.       (null x)
  808.     (error "endp received a non-cons, non-null argument `%s'"
  809.        (prin1-to-string x))))
  810.  
  811. (defun last (x)
  812.   "Returns the last link in the list LIST."
  813.   (if (nlistp x)
  814.       (error "Arg to `last' must be a list"))
  815.   (do ((current-cons    x       (cdr current-cons))
  816.        (next-cons    (cdr x)    (cdr next-cons)))
  817.       ((endp next-cons) current-cons)))
  818.  
  819. (defun list-length (x)                  ;taken from CLtL sect. 15.2
  820.   "Returns the length of a non-circular list, or `nil' for a circular one."
  821.   (do ((n 0)                            ;counter
  822.        (fast x (cddr fast))             ;fast pointer, leaps by 2
  823.        (slow x (cdr slow))              ;slow pointer, leaps by 1
  824.        (ready nil))                     ;indicates termination
  825.       (ready n)
  826.     (cond
  827.      ((endp fast)
  828.       (setq ready t))                   ;return n
  829.      ((endp (cdr fast))
  830.       (setq n (+ n 1))
  831.       (setq ready t))                   ;return n+1
  832.      ((and (eq fast slow) (> n 0))
  833.       (setq n nil)
  834.       (setq ready t))                   ;return nil
  835.      (t
  836.       (setq n (+ n 2))))))              ;just advance counter
  837.  
  838. ;; Renamed from `member' since we might define traditional `member'.
  839. (defun cl-member (item list)
  840.   "Look for ITEM in LIST; return first link in LIST whose car is `eql' to ITEM."
  841.   (let ((ptr list)
  842.         (done nil)
  843.         (result '()))
  844.     (while (not (or done (endp ptr)))
  845.       (cond ((eql item (car ptr))
  846.              (setq done t)
  847.              (setq result ptr)))
  848.       (setq ptr (cdr ptr)))
  849.     result))
  850.  
  851. (defun butlast (list &optional n)
  852.   "Return a new list like LIST but sans the last N elements.
  853. N defaults to 1.  If the list doesn't have N elements, nil is returned."
  854.   (if (null n) (setq n 1))
  855.   (reverse (nthcdr n (reverse list))))
  856.  
  857. (defun list* (arg &rest others)
  858.   "Return a new list containing the first arguments consed onto the last arg.
  859. Thus, (list* 1 2 3 '(a b)) returns (1 2 3 a b)."
  860.   (if (null others)
  861.       arg
  862.     (let* ((allargs (cons arg others))
  863.            (front   (butlast allargs))
  864.            (back    (last allargs)))
  865.       (rplacd (last front) (car back))
  866.       front)))
  867.  
  868. (defun adjoin (item list)
  869.   "Return a list which contains ITEM but is otherwise like LIST.
  870. If ITEM occurs in LIST, the value is LIST.  Otherwise it is (cons ITEM LIST).
  871. When comparing ITEM against elements, `eql' is used."
  872.   (cond
  873.    ((cl-member item list)
  874.     list)
  875.    (t
  876.     (cons item list))))
  877.  
  878. (defun ldiff (list sublist)
  879.   "Return a new list like LIST but sans SUBLIST.
  880. SUBLIST must be one of the links in LIST; otherwise the value is LIST itself."
  881.   (do ((result '())
  882.        (curcons list (cdr curcons)))
  883.       ((or (endp curcons) (eq curcons sublist))
  884.        (reverse result))
  885.     (setq result (cons (car curcons) result))))
  886.  
  887. ;;; The popular c[ad]*r functions.
  888.  
  889. (defun caar (X)
  890.   "Return the car of the car of X."
  891.   (car (car X)))
  892.  
  893. (defun cadr (X)
  894.   "Return the car of the cdr of X."
  895.   (car (cdr X)))
  896.  
  897. (defun cdar (X)
  898.   "Return the cdr of the car of X."
  899.   (cdr (car X)))
  900.  
  901. (defun cddr (X)
  902.   "Return the cdr of the cdr of X."
  903.   (cdr (cdr X)))
  904.  
  905. (defun caaar (X)
  906.   "Return the car of the car of the car of X."
  907.   (car (car (car X))))
  908.  
  909. (defun caadr (X)
  910.   "Return the car of the car of the cdr of X."
  911.   (car (car (cdr X))))
  912.  
  913. (defun cadar (X)
  914.   "Return the car of the cdr of the car of X."
  915.   (car (cdr (car X))))
  916.  
  917. (defun cdaar (X)
  918.   "Return the cdr of the car of the car of X."
  919.   (cdr (car (car X))))
  920.  
  921. (defun caddr (X)
  922.   "Return the car of the cdr of the cdr of X."
  923.   (car (cdr (cdr X))))
  924.  
  925. (defun cdadr (X)
  926.   "Return the cdr of the car of the cdr of X."
  927.   (cdr (car (cdr X))))
  928.  
  929. (defun cddar (X)
  930.   "Return the cdr of the cdr of the car of X."
  931.   (cdr (cdr (car X))))
  932.  
  933. (defun cdddr (X)
  934.   "Return the cdr of the cdr of the cdr of X."
  935.   (cdr (cdr (cdr X))))
  936.  
  937. (defun caaaar (X)
  938.   "Return the car of the car of the car of the car of X."
  939.   (car (car (car (car X)))))
  940.  
  941. (defun caaadr (X)
  942.   "Return the car of the car of the car of the cdr of X."
  943.   (car (car (car (cdr X)))))
  944.  
  945. (defun caadar (X)
  946.   "Return the car of the car of the cdr of the car of X."
  947.   (car (car (cdr (car X)))))
  948.  
  949. (defun cadaar (X)
  950.   "Return the car of the cdr of the car of the car of X."
  951.   (car (cdr (car (car X)))))
  952.  
  953. (defun cdaaar (X)
  954.   "Return the cdr of the car of the car of the car of X."
  955.   (cdr (car (car (car X)))))
  956.  
  957. (defun caaddr (X)
  958.   "Return the car of the car of the cdr of the cdr of X."
  959.   (car (car (cdr (cdr X)))))
  960.  
  961. (defun cadadr (X)
  962.   "Return the car of the cdr of the car of the cdr of X."
  963.   (car (cdr (car (cdr X)))))
  964.  
  965. (defun cdaadr (X)
  966.   "Return the cdr of the car of the car of the cdr of X."
  967.   (cdr (car (car (cdr X)))))
  968.  
  969. (defun caddar (X)
  970.   "Return the car of the cdr of the cdr of the car of X."
  971.   (car (cdr (cdr (car X)))))
  972.  
  973. (defun cdadar (X)
  974.   "Return the cdr of the car of the cdr of the car of X."
  975.   (cdr (car (cdr (car X)))))
  976.  
  977. (defun cddaar (X)
  978.   "Return the cdr of the cdr of the car of the car of X."
  979.   (cdr (cdr (car (car X)))))
  980.  
  981. (defun cadddr (X)
  982.   "Return the car of the cdr of the cdr of the cdr of X."
  983.   (car (cdr (cdr (cdr X)))))
  984.  
  985. (defun cddadr (X)
  986.   "Return the cdr of the cdr of the car of the cdr of X."
  987.   (cdr (cdr (car (cdr X)))))
  988.  
  989. (defun cdaddr (X)
  990.   "Return the cdr of the car of the cdr of the cdr of X."
  991.   (cdr (car (cdr (cdr X)))))
  992.  
  993. (defun cdddar (X)
  994.   "Return the cdr of the cdr of the cdr of the car of X."
  995.   (cdr (cdr (cdr (car X)))))
  996.  
  997. (defun cddddr (X)
  998.   "Return the cdr of the cdr of the cdr of the cdr of X."
  999.   (cdr (cdr (cdr (cdr X)))))
  1000.  
  1001. ;;; some inverses of the accessors are needed for setf purposes
  1002.  
  1003. (defun setnth (n list newval)
  1004.   "Set (nth N LIST) to NEWVAL.  Returns NEWVAL."
  1005.   (rplaca (nthcdr n list) newval))
  1006.  
  1007. (defun setnthcdr (n list newval)
  1008.   "SETNTHCDR N LIST NEWVAL => NEWVAL
  1009. As a side effect, sets the Nth cdr of LIST to NEWVAL."
  1010.   (cond
  1011.    ((< n 0)
  1012.     (error "N must be 0 or greater, not %d" n))
  1013.    ((= n 0)
  1014.     (rplaca list (car newval))
  1015.     (rplacd list (cdr newval))
  1016.     newval)
  1017.    (t
  1018.     (rplacd (nthcdr (- n 1) list) newval))))
  1019.  
  1020. ;;; A-lists machinery
  1021.  
  1022. (defun acons (key item alist)
  1023.   "Return a new alist with KEY paired with ITEM; otherwise like ALIST.
  1024. Does not copy ALIST."
  1025.   (cons (cons key item) alist))
  1026.  
  1027. (defun pairlis (keys data &optional alist)
  1028.   "Return a new alist with each elt of KEYS paired with an elt of DATA;
  1029. optional 3rd arg ALIST is nconc'd at the end.  KEYS and DATA must
  1030. have the same length."
  1031.   (unless (= (length keys) (length data))
  1032.     (error "Keys and data should be the same length"))
  1033.   (do* ;;collect keys and data in front of alist
  1034.       ((kptr keys (cdr kptr))           ;traverses the keys
  1035.        (dptr data (cdr dptr))           ;traverses the data
  1036.        (key (car kptr) (car kptr))      ;current key
  1037.        (item (car dptr) (car dptr))     ;current data item
  1038.        (result alist))
  1039.       ((endp kptr) result)
  1040.     (setq result (acons key item result))))
  1041.  
  1042. ;;;; end of cl-lists.el
  1043.  
  1044. ;;;; SEQUENCES
  1045. ;;;; Emacs Lisp provides many of the 'sequences' functionality of
  1046. ;;;; Common Lisp.  This file provides a few things that were left out.
  1047. ;;;; 
  1048.  
  1049.  
  1050. (defkeyword :test      "Used to designate positive (selection) tests.")
  1051. (defkeyword :test-not  "Used to designate negative (rejection) tests.")
  1052. (defkeyword :key       "Used to designate component extractions.")
  1053. (defkeyword :predicate "Used to define matching of sequence components.")
  1054. (defkeyword :start     "Inclusive low index in sequence")
  1055. (defkeyword :end       "Exclusive high index in sequence")
  1056. (defkeyword :start1    "Inclusive low index in first of two sequences.")
  1057. (defkeyword :start2    "Inclusive low index in second of two sequences.")
  1058. (defkeyword :end1      "Exclusive high index in first of two sequences.")
  1059. (defkeyword :end2      "Exclusive high index in second of two sequences.")
  1060. (defkeyword :count     "Number of elements to affect.")
  1061. (defkeyword :from-end  "T when counting backwards.")
  1062.  
  1063. (defun some     (pred seq &rest moreseqs)
  1064.   "Test PREDICATE on each element of SEQUENCE; is it ever non-nil?
  1065. Extra args are additional sequences; PREDICATE gets one arg from each
  1066. sequence and we advance down all the sequences together in lock-step.
  1067. A sequence means either a list or a vector."
  1068.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1069.     (do* ((ready nil)                   ;flag: return when t
  1070.           (result nil)                  ;resulting value
  1071.           (applyval nil)                ;result of applying pred once
  1072.           (remaining args
  1073.                      (cdr remaining))   ;remaining argument sets
  1074.           (current (car remaining)      ;current argument set
  1075.                    (car remaining)))
  1076.         ((or ready (endp remaining)) result)
  1077.       (setq applyval (apply pred current))
  1078.       (when applyval
  1079.         (setq ready t)
  1080.         (setq result applyval)))))
  1081.  
  1082. (defun every    (pred seq &rest moreseqs)
  1083.   "Test PREDICATE on each element of SEQUENCE; is it always non-nil?
  1084. Extra args are additional sequences; PREDICATE gets one arg from each
  1085. sequence and we advance down all the sequences together in lock-step.
  1086. A sequence means either a list or a vector."
  1087.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1088.     (do* ((ready nil)                   ;flag: return when t
  1089.           (result t)                    ;resulting value
  1090.           (applyval nil)                ;result of applying pred once
  1091.           (remaining args
  1092.                      (cdr remaining))   ;remaining argument sets
  1093.           (current (car remaining)      ;current argument set
  1094.                    (car remaining)))
  1095.         ((or ready (endp remaining)) result)
  1096.       (setq applyval (apply pred current))
  1097.       (unless applyval
  1098.         (setq ready t)
  1099.         (setq result nil)))))
  1100.  
  1101. (defun notany   (pred seq &rest moreseqs)
  1102.   "Test PREDICATE on each element of SEQUENCE; is it always nil?
  1103. Extra args are additional sequences; PREDICATE gets one arg from each
  1104. sequence and we advance down all the sequences together in lock-step.
  1105. A sequence means either a list or a vector."
  1106.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1107.     (do* ((ready nil)                   ;flag: return when t
  1108.           (result t)                    ;resulting value
  1109.           (applyval nil)                ;result of applying pred once
  1110.           (remaining args
  1111.                      (cdr remaining))   ;remaining argument sets
  1112.           (current (car remaining)      ;current argument set
  1113.                    (car remaining)))
  1114.         ((or ready (endp remaining)) result)
  1115.       (setq applyval (apply pred current))
  1116.       (when applyval
  1117.         (setq ready t)
  1118.         (setq result nil)))))
  1119.  
  1120. (defun notevery (pred seq &rest moreseqs)
  1121.   "Test PREDICATE on each element of SEQUENCE; is it sometimes nil?
  1122. Extra args are additional sequences; PREDICATE gets one arg from each
  1123. sequence and we advance down all the sequences together in lock-step.
  1124. A sequence means either a list or a vector."
  1125.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1126.     (do* ((ready nil)                   ;flag: return when t
  1127.           (result nil)                  ;resulting value
  1128.           (applyval nil)                ;result of applying pred once
  1129.           (remaining args
  1130.                      (cdr remaining))   ;remaining argument sets
  1131.           (current (car remaining)      ;current argument set
  1132.                    (car remaining)))
  1133.         ((or ready (endp remaining)) result)
  1134.       (setq applyval (apply pred current))
  1135.       (unless applyval
  1136.         (setq ready t)
  1137.         (setq result t)))))
  1138.  
  1139.  
  1140.  
  1141. ;;; an inverse of elt is needed for setf purposes
  1142.  
  1143. (defun setelt (seq n newval)
  1144.   "In SEQUENCE, set the Nth element to NEWVAL.  Returns NEWVAL.
  1145. A sequence means either a list or a vector."
  1146.   (let ((l (length seq)))
  1147.     (cond
  1148.      ((or (< n 0)
  1149.           (>= n l))
  1150.       (error "N(%d) should be between 0 and %d" n l))
  1151.      (t
  1152.       ;; only two cases need be considered
  1153.       (cond
  1154.        ((listp seq)
  1155.         (setnth n seq newval))
  1156.        ((arrayp seq)
  1157.         (aset seq n newval))
  1158.        (t
  1159.         (error "SEQ should be a sequence, not `%s'"
  1160.                (prin1-to-string seq))))))))
  1161.  
  1162. ;;; Testing with keyword arguments.
  1163. ;;;
  1164. ;;; Many of the sequence functions use keywords to denote some stylized
  1165. ;;; form of selecting entries in a sequence.  The involved arguments
  1166. ;;; are collected with a &rest marker (as Emacs Lisp doesn't have a &key
  1167. ;;; marker), then they are passed to build-klist, who
  1168. ;;; constructs an association list.  That association list is used to
  1169. ;;; test for satisfaction and matching.
  1170.  
  1171. (defun extract-from-klist (key klist &optional default)
  1172.   "EXTRACT-FROM-KLIST KEY KLIST [DEFAULT] => value of KEY or DEFAULT
  1173. Extract value associated with KEY in KLIST (return DEFAULT if nil)."
  1174.   (let ((retrieved (cdr (assoc key klist))))
  1175.     (or retrieved default)))
  1176.  
  1177. (defun add-to-klist (key item klist)
  1178.   "ADD-TO-KLIST KEY ITEM KLIST => new KLIST
  1179. Add association (KEY . ITEM) to KLIST."
  1180.   (setq klist (acons key item klist)))
  1181.  
  1182. (defun elt-satisfies-test-p (item elt klist)
  1183.   "ELT-SATISFIES-TEST-P ITEM ELT KLIST => t or nil
  1184. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1185. True if the given ITEM and ELT satisfy the test."
  1186.   (let ((test     (extract-from-klist :test klist))
  1187.         (test-not (extract-from-klist :test-not klist))
  1188.         (keyfn    (extract-from-klist :key klist 'identity)))
  1189.     (cond
  1190.      (test
  1191.       (funcall test item (funcall keyfn elt)))
  1192.      (test-not
  1193.       (not (funcall test-not item (funcall keyfn elt))))
  1194.      (t                                 ;should never happen
  1195.       (error "Neither :test nor :test-not in `%s'"
  1196.              (prin1-to-string klist))))))
  1197.  
  1198. (defun elt-satisfies-if-p   (item klist)
  1199.   "ELT-SATISFIES-IF-P ITEM KLIST => t or nil
  1200. True if an -if style function was called and ITEM satisfies the
  1201. predicate under :predicate in KLIST."
  1202.   (let ((predicate (extract-from-klist :predicate klist))
  1203.         (keyfn     (extract-from-klist :key 'identity)))
  1204.     (funcall predicate item (funcall keyfn elt))))
  1205.  
  1206. (defun elt-satisfies-if-not-p (item klist)
  1207.   "ELT-SATISFIES-IF-NOT-P ITEM KLIST => t or nil
  1208. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1209. True if an -if-not style function was called and ITEM does not satisfy
  1210. the predicate under :predicate in KLIST."
  1211.   (let ((predicate (extract-from-klist :predicate klist))
  1212.         (keyfn     (extract-from-klist :key 'identity)))
  1213.     (not (funcall predicate item (funcall keyfn elt)))))
  1214.  
  1215. (defun elts-match-under-klist-p (e1 e2 klist)
  1216.   "ELTS-MATCH-UNDER-KLIST-P E1 E2 KLIST => t or nil
  1217. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1218. True if elements E1 and E2 match under the tests encoded in KLIST."
  1219.   (let ((test     (extract-from-klist :test klist))
  1220.         (test-not (extract-from-klist :test-not klist))
  1221.         (keyfn    (extract-from-klist :key klist 'identity)))
  1222.     (cond
  1223.      (test
  1224.       (funcall test (funcall keyfn e1) (funcall keyfn e2)))
  1225.      (test-not
  1226.       (not (funcall test-not (funcall keyfn e1) (funcall keyfn e2))))
  1227.      (t                                 ;should never happen
  1228.       (error "Neither :test nor :test-not in `%s'"
  1229.              (prin1-to-string klist))))))
  1230.  
  1231. ;;;; end of cl-sequences.el
  1232.  
  1233. ;;;; MULTIPLE VALUES
  1234. ;;;;    This package approximates the behavior of the multiple-values
  1235. ;;;;    forms of Common Lisp.  
  1236. ;;;;
  1237. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1238. ;;;;       (quiroz@cs.rochester.edu)
  1239.  
  1240.  
  1241.  
  1242. ;;; Lisp indentation information
  1243. (put 'multiple-value-bind  'lisp-indent-function 2)
  1244. (put 'multiple-value-setq  'lisp-indent-function 2)
  1245. (put 'multiple-value-list  'lisp-indent-function nil)
  1246. (put 'multiple-value-call  'lisp-indent-function 1)
  1247. (put 'multiple-value-prog1 'lisp-indent-function 1)
  1248.  
  1249.  
  1250. ;;; Global state of the package is kept here
  1251. (defvar *mvalues-values* nil
  1252.   "Most recently returned multiple-values")
  1253. (defvar *mvalues-count*  nil
  1254.   "Count of multiple-values returned, or nil if the mechanism was not used")
  1255.  
  1256. ;;; values is the standard multiple-value-return form.  Must be the
  1257. ;;; last thing evaluated inside a function.  If the caller is not
  1258. ;;; expecting multiple values, only the first one is passed.  (values)
  1259. ;;; is the same as no-values returned (unaware callers see nil). The
  1260. ;;; alternative (values-list <list>) is just a convenient shorthand
  1261. ;;; and complements multiple-value-list.
  1262.  
  1263. (defun values (&rest val-forms)
  1264.   "Produce multiple values (zero or more).  Each arg is one value.
  1265. See also `multiple-value-bind', which is one way to examine the
  1266. multiple values produced by a form.  If the containing form or caller
  1267. does not check specially to see multiple values, it will see only
  1268. the first value."
  1269.   (setq *mvalues-values* val-forms)
  1270.   (setq *mvalues-count*  (length *mvalues-values*))
  1271.   (car *mvalues-values*))
  1272.  
  1273.  
  1274. (defun values-list (&optional val-forms)
  1275.   "Produce multiple values (zero or mode).  Each element of LIST is one value.
  1276. This is equivalent to (apply 'values LIST)."
  1277.   (cond ((nlistp val-forms)
  1278.          (error "Argument to values-list must be a list, not `%s'"
  1279.                 (prin1-to-string val-forms))))
  1280.   (setq *mvalues-values* val-forms)
  1281.   (setq *mvalues-count* (length *mvalues-values*))
  1282.   (car *mvalues-values*))
  1283.  
  1284.  
  1285. ;;; Callers that want to see the multiple values use these macros.
  1286.  
  1287. (defmacro multiple-value-list (form)
  1288.   "Execute FORM and return a list of all the (multiple) values FORM produces.
  1289. See `values' and `multiple-value-bind'."
  1290.   (list 'progn
  1291.         (list 'setq '*mvalues-count* nil)
  1292.         (list 'let (list (list 'it '(gensym)))
  1293.               (list 'set 'it form)
  1294.               (list 'if '*mvalues-count*
  1295.                     (list 'copy-sequence '*mvalues-values*)
  1296.                     (list 'progn
  1297.                           (list 'setq '*mvalues-count* 1)
  1298.                           (list 'setq '*mvalues-values*
  1299.                                 (list 'list (list 'symbol-value 'it)))
  1300.                           (list 'copy-sequence '*mvalues-values*))))))
  1301.  
  1302. (defmacro multiple-value-call (function &rest args)
  1303.   "Call FUNCTION on all the values produced by the remaining arguments.
  1304. (multiple-value-call '+ (values 1 2) (values 3 4)) is 10."
  1305.   (let* ((result (gentemp))
  1306.          (arg    (gentemp)))
  1307.     (list 'apply (list 'function (eval function))
  1308.           (list 'let* (list (list result '()))
  1309.                 (list 'dolist (list arg (list 'quote args) result)
  1310.                       (list 'setq result
  1311.                             (list 'append
  1312.                                   result
  1313.                                   (list 'multiple-value-list
  1314.                                         (list 'eval arg)))))))))
  1315.  
  1316. (defmacro multiple-value-bind (vars form &rest body)
  1317.   "Bind VARS to the (multiple) values produced by FORM, then do BODY.
  1318. VARS is a list of variables; each is bound to one of FORM's values.
  1319. If FORM doesn't make enough values, the extra variables are bound to nil.
  1320. (Ordinary forms produce only one value; to produce more, use `values'.)
  1321. Extra values are ignored.
  1322. BODY (zero or more forms) is executed with the variables bound,
  1323. then the bindings are unwound."
  1324.   (let* ((vals   (gentemp))             ;name for intermediate values
  1325.          (clauses (mv-bind-clausify     ;convert into clauses usable
  1326.                    vars vals)))         ; in a let form
  1327.     (list* 'let*
  1328.            (cons (list vals (list 'multiple-value-list form))
  1329.                  clauses)
  1330.            body)))
  1331.  
  1332. (defmacro multiple-value-setq (vars form)
  1333.   "Set VARS to the (multiple) values produced by FORM.
  1334. VARS is a list of variables; each is set to one of FORM's values.
  1335. If FORM doesn't make enough values, the extra variables are set to nil.
  1336. (Ordinary forms produce only one value; to produce more, use `values'.)
  1337. Extra values are ignored."
  1338.   (let* ((vals (gentemp))               ;name for intermediate values
  1339.          (clauses (mv-bind-clausify     ;convert into clauses usable
  1340.                    vars vals)))         ; in a setq (after append).
  1341.     (list 'let*
  1342.           (list (list vals (list 'multiple-value-list form)))
  1343.           (cons 'setq (apply (function append) clauses)))))
  1344.  
  1345. (defmacro multiple-value-prog1 (form &rest body)
  1346.   "Evaluate FORM, then BODY, then produce the same values FORM produced.
  1347. Thus, (multiple-value-prog1 (values 1 2) (foobar)) produces values 1 and 2.
  1348. This is like `prog1' except that `prog1' would produce only one value,
  1349. which would be the first of FORM's values."
  1350.   (let* ((heldvalues (gentemp)))
  1351.     (cons 'let*
  1352.           (cons (list (list heldvalues (list 'multiple-value-list form)))
  1353.                 (append body (list (list 'values-list heldvalues)))))))
  1354.  
  1355. ;;; utility functions
  1356. ;;;
  1357. ;;; mv-bind-clausify makes the pairs needed to have the variables in
  1358. ;;; the variable list correspond with the values returned by the form.
  1359. ;;; vals is a fresh symbol that intervenes in all the bindings.
  1360.  
  1361. (defun mv-bind-clausify (vars vals)
  1362.   "MV-BIND-CLAUSIFY VARS VALS => Auxiliary list
  1363. Forms a list of pairs `(,(nth i vars) (nth i vals)) for i from 0 to
  1364. the length of VARS (a list of symbols).  VALS is just a fresh symbol."
  1365.   (if (or (nlistp vars)
  1366.           (notevery 'symbolp vars))
  1367.       (error "Expected a list of symbols, not `%s'"
  1368.              (prin1-to-string vars)))
  1369.   (let* ((nvars    (length vars))
  1370.          (clauses '()))
  1371.     (dotimes (n nvars clauses)
  1372.       (setq clauses (cons (list (nth n vars)
  1373.                                 (list 'nth n vals)) clauses)))))
  1374.  
  1375. ;;;; end of cl-multiple-values.el
  1376.  
  1377. ;;;; ARITH
  1378. ;;;;    This file provides integer arithmetic extensions.  Although
  1379. ;;;;    Emacs Lisp doesn't really support anything but integers, that
  1380. ;;;;    has still to be made to look more or less standard.
  1381. ;;;;
  1382. ;;;;
  1383. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1384. ;;;;       (quiroz@cs.rochester.edu)
  1385.  
  1386.  
  1387. (defun plusp (number)
  1388.   "True if NUMBER is strictly greater than zero."
  1389.   (> number 0))
  1390.  
  1391. (defun minusp (number)
  1392.   "True if NUMBER is strictly less than zero."
  1393.   (< number 0))
  1394.  
  1395. (defun oddp (number)
  1396.   "True if INTEGER is not divisible by 2."
  1397.   (/= (% number 2) 0))
  1398.  
  1399. (defun evenp (number)
  1400.   "True if INTEGER is divisible by 2."
  1401.   (= (% number 2) 0))
  1402.  
  1403. (defun abs (number)
  1404.   "Return the absolute value of NUMBER."
  1405.   (cond
  1406.    ((< number 0)
  1407.     (- 0 number))
  1408.    (t                                   ;number is >= 0
  1409.     number)))
  1410.  
  1411. (defun signum (number)
  1412.   "Return -1, 0 or 1 according to the sign of NUMBER."
  1413.   (cond
  1414.    ((< number 0)
  1415.     -1)
  1416.    ((> number 0)
  1417.     1)
  1418.    (t                                   ;exactly zero
  1419.     0)))
  1420.  
  1421. (defun gcd (&rest integers)
  1422.   "Return the greatest common divisor of all the arguments.
  1423. The arguments must be integers.  With no arguments, value is zero."
  1424.   (let ((howmany (length integers)))
  1425.     (cond
  1426.      ((= howmany 0)
  1427.       0)
  1428.      ((= howmany 1)
  1429.       (abs (car integers)))
  1430.      ((> howmany 2)
  1431.       (apply (function gcd)
  1432.        (cons (gcd (nth 0 integers) (nth 1 integers))
  1433.              (nthcdr 2 integers))))
  1434.      (t                                 ;howmany=2
  1435.       ;; essentially the euclidean algorithm
  1436.       (when (zerop (* (nth 0 integers) (nth 1 integers)))
  1437.         (error "A zero argument is invalid for `gcd'"))
  1438.       (do* ((absa (abs (nth 0 integers))) ; better to operate only
  1439.             (absb (abs (nth 1 integers))) ;on positives.
  1440.             (dd (max absa absb))        ; setup correct order for the
  1441.             (ds (min absa absb))        ;succesive divisions.
  1442.             ;; intermediate results
  1443.             (q 0)
  1444.             (r 0)
  1445.             ;; final results
  1446.             (done nil)                  ; flag: end of iterations
  1447.             (result 0))                 ; final value
  1448.           (done result)
  1449.         (setq q (/ dd ds))
  1450.         (setq r (% dd ds))
  1451.         (cond 
  1452.          ((zerop r) (setq done t) (setq result ds))
  1453.          ( t        (setq dd ds)  (setq ds r))))))))
  1454.  
  1455. (defun lcm (integer &rest more)
  1456.   "Return the least common multiple of all the arguments.
  1457. The arguments must be integers and there must be at least one of them."
  1458.   (let ((howmany (length more))
  1459.         (a       integer)
  1460.         (b       (nth 0 more))
  1461.         prod                            ; intermediate product
  1462.         (yetmore (nthcdr 1 more)))
  1463.     (cond
  1464.      ((zerop howmany)
  1465.       (abs a))
  1466.      ((> howmany 1)                     ; recursive case
  1467.       (apply (function lcm)
  1468.              (cons (lcm a b) yetmore)))
  1469.      (t                                 ; base case, just 2 args
  1470.       (setq prod (* a b))
  1471.       (cond
  1472.        ((zerop prod)
  1473.         0)
  1474.        (t
  1475.         (/ (abs prod) (gcd a b))))))))
  1476.  
  1477. (defun isqrt (number)
  1478.   "Return the integer square root of NUMBER.
  1479. NUMBER must not be negative.  Result is largest integer less than or
  1480. equal to the real square root of the argument."
  1481.   ;; The method used here is essentially the Newtonian iteration
  1482.   ;;    x[n+1] <- (x[n] + Number/x[n]) / 2
  1483.   ;; suitably adapted to integer arithmetic.
  1484.   ;; Thanks to Philippe Schnoebelen <phs@lifia.imag.fr> for suggesting the
  1485.   ;; termination condition.
  1486.   (cond ((minusp number)
  1487.          (error "Argument to `isqrt' (%d) must not be negative"
  1488.                 number))
  1489.         ((zerop number)
  1490.          0)
  1491.         (t                              ;so (> number 0)
  1492.          (do* ((approx 1)               ;any positive integer will do
  1493.                (new 0)                  ;init value irrelevant
  1494.                (done nil))
  1495.              (done (if (> (* approx approx) number)
  1496.                        (- approx 1)
  1497.                      approx))
  1498.            (setq new    (/ (+ approx (/ number approx)) 2)
  1499.                  done   (or (= new approx) (= new (+ approx 1)))
  1500.                  approx new)))))
  1501.  
  1502. (defun floor (number &optional divisor)
  1503.   "Divide DIVIDEND by DIVISOR, rounding toward minus infinity.
  1504. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1505.   (cond
  1506.    ((and (null divisor)                 ; trivial case
  1507.          (numberp number))
  1508.     (values number 0))
  1509.    (t                                   ; do the division
  1510.     (multiple-value-bind
  1511.         (q r s)
  1512.         (safe-idiv number divisor)
  1513.       (cond
  1514.        ((zerop s)
  1515.         (values 0 0))
  1516.        ((plusp s)
  1517.         (values q r))
  1518.        (t (if (zerop r)
  1519.           (values (- 0 q) 0)
  1520.         (let ((q (- 0 (+ q 1))))
  1521.           (values q (- number (* q divisor)))))))))))
  1522.  
  1523. (defun ceiling (number &optional divisor)
  1524.   "Divide DIVIDEND by DIVISOR, rounding toward plus infinity.
  1525. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1526.   (cond
  1527.    ((and (null divisor)                 ; trivial case
  1528.          (numberp number))
  1529.     (values number 0))
  1530.    (t                                   ; do the division
  1531.     (multiple-value-bind
  1532.         (q r s)
  1533.         (safe-idiv number divisor)
  1534.       (cond
  1535.        ((zerop s)
  1536.         (values 0 0))
  1537.        ((minusp s)
  1538.         (values q r))
  1539.        (t
  1540.         (unless (zerop r)
  1541.           (setq q (+ q 1))
  1542.           (setq r (- number (* q divisor))))
  1543.         (values q r)))))))
  1544.  
  1545. (defun truncate (number &optional divisor)
  1546.   "Divide DIVIDEND by DIVISOR, rounding toward zero.
  1547. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1548.   (cond
  1549.    ((and (null divisor)                 ; trivial case
  1550.          (numberp number))
  1551.     (values number 0))
  1552.    (t                                   ; do the division
  1553.     (multiple-value-bind
  1554.         (q r s)
  1555.         (safe-idiv number divisor)
  1556.       (cond
  1557.        ((zerop s)
  1558.         (values 0 0))
  1559.        ((plusp s)
  1560.         (values q r))
  1561.        (t
  1562.         (unless (zerop r)
  1563.           (setq q (- 0 q))
  1564.           (setq r (- number (* q divisor))))
  1565.         (values q r)))))))
  1566.  
  1567. (defun round (number &optional divisor)
  1568.   "Divide DIVIDEND by DIVISOR, rounding to nearest integer.
  1569. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1570.   (cond
  1571.    ((and (null divisor)                 ; trivial case
  1572.          (numberp number))
  1573.     (values number 0))    
  1574.    (t                                   ; do the division
  1575.     (multiple-value-bind
  1576.         (q r s)
  1577.         (safe-idiv number divisor)
  1578.       (setq r (abs r))
  1579.       ;; adjust magnitudes first, and then signs
  1580.       (let ((other-r (- (abs divisor) r)))
  1581.         (cond
  1582.          ((> r other-r)
  1583.           (setq q (+ q 1)))
  1584.          ((and (= r other-r)
  1585.                (oddp q))
  1586.           ;; round to even is mandatory
  1587.           (setq q (+ q 1))))
  1588.         (setq q (* s q))
  1589.         (setq r (- number (* q divisor)))
  1590.         (values q r))))))
  1591.  
  1592. (defun mod (number divisor)
  1593.   "Return remainder of X by Y (rounding quotient toward minus infinity).
  1594. That is, the remainder goes with the quotient produced by `floor'."
  1595.   (multiple-value-bind (q r) (floor number divisor)
  1596.     r))
  1597.  
  1598. (defun rem (number divisor)
  1599.   "Return remainder of X by Y (rounding quotient toward zero).
  1600. That is, the remainder goes with the quotient produced by `truncate'."
  1601.   (multiple-value-bind (q r) (truncate number divisor)
  1602.     r))
  1603.  
  1604. ;;; internal utilities
  1605. ;;;
  1606. ;;; safe-idiv performs an integer division with positive numbers only.
  1607. ;;; It is known that some machines/compilers implement weird remainder
  1608. ;;; computations when working with negatives, so the idea here is to
  1609. ;;; make sure we know what is coming back to the caller in all cases.
  1610.  
  1611. (defun safe-idiv (a b)
  1612.   "SAFE-IDIV A B => Q R S
  1613. Q=|A|/|B|, R is the rest, S is the sign of A/B."
  1614.   (unless (and (numberp a) (numberp b))
  1615.     (error "Arguments to `safe-idiv' must be numbers"))
  1616.   (when (zerop b)
  1617.     (error "Cannot divide %d by zero" a))
  1618.   (let* ((absa (abs a))
  1619.          (absb (abs b))
  1620.          (q    (/ absa absb))
  1621.          (s    (* (signum a) (signum b)))
  1622.          (r    (- a (* (* s q) b))))
  1623.     (values q r s)))
  1624.  
  1625. ;;;; end of cl-arith.el
  1626.  
  1627. ;;;; SETF
  1628. ;;;;    This file provides the setf macro and friends. The purpose has
  1629. ;;;;    been modest, only the simplest defsetf forms are accepted.
  1630. ;;;;    Use it and enjoy.
  1631. ;;;;
  1632. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1633. ;;;;       (quiroz@cs.rochester.edu)
  1634.  
  1635.  
  1636. (defkeyword :setf-update-fn
  1637.   "Property, its value is the function setf must invoke to update a
  1638. generalized variable whose access form is a function call of the
  1639. symbol that has this property.")
  1640.  
  1641. (defkeyword :setf-update-doc
  1642.   "Property of symbols that have a `defsetf' update function on them,
  1643. installed by the `defsetf' from its optional third argument.")
  1644.  
  1645. (defmacro setf (&rest pairs)
  1646.   "Generalized `setq' that can set things other than variable values.
  1647. A use of `setf' looks like (setf {PLACE VALUE}...).
  1648. The behavior of (setf PLACE VALUE) is to access the generalized variable
  1649. at PLACE and store VALUE there.  It returns VALUE.  If there is more
  1650. than one PLACE and VALUE, each PLACE is set from its VALUE before
  1651. the next PLACE is evaluated."
  1652.   (let ((nforms (length pairs)))
  1653.     ;; check the number of subforms
  1654.     (cond
  1655.      ((/= (% nforms 2) 0)
  1656.       (error "Odd number of arguments to `setf'"))
  1657.      ((= nforms 0)
  1658.       nil)
  1659.      ((> nforms 2)
  1660.       ;; this is the recursive case
  1661.       (cons 'progn
  1662.             (do*                        ;collect the place-value pairs
  1663.                 ((args pairs (cddr args))
  1664.                  (place (car args) (car args))
  1665.                  (value (cadr args) (cadr args))
  1666.                  (result '()))
  1667.                 ((endp args) (nreverse result))
  1668.               (setq result
  1669.                     (cons (list 'setf place value)
  1670.                           result)))))
  1671.      (t                                 ;i.e., nforms=2
  1672.       ;; this is the base case (SETF PLACE VALUE)
  1673.       (let* ((place (car pairs))
  1674.              (value (cadr pairs))
  1675.              (head  nil)
  1676.              (updatefn nil))
  1677.         ;; dispatch on the type of the PLACE
  1678.         (cond
  1679.          ((symbolp place)
  1680.           (list 'setq place value))
  1681.          ((and (listp place)
  1682.                (setq head (car place))
  1683.                (symbolp head)
  1684.                (setq updatefn (get head :setf-update-fn)))
  1685.       (if (or (and (consp updatefn) (eq (car updatefn) 'lambda))
  1686.           (and (symbolp updatefn)
  1687.                (fboundp updatefn)
  1688.                (let ((defn (symbol-function updatefn)))
  1689.              (or (subrp defn)
  1690.                  (and (consp defn) (eq (car defn) 'lambda))))))
  1691.           (cons updatefn (append (cdr place) (list value)))
  1692.         (multiple-value-bind
  1693.         (bindings newsyms)
  1694.         (pair-with-newsyms (append (cdr place) (list value)))
  1695.           ;; this let* gets new symbols to ensure adequate order of
  1696.           ;; evaluation of the subforms.
  1697.           (list 'let
  1698.             bindings              
  1699.             (cons updatefn newsyms)))))
  1700.          (t
  1701.           (error "No `setf' update-function for `%s'"
  1702.                  (prin1-to-string place)))))))))
  1703.  
  1704. (defmacro defsetf (accessfn updatefn &optional docstring)
  1705.   "Define how `setf' works on a certain kind of generalized variable.
  1706. A use of `defsetf' looks like (defsetf ACCESSFN UPDATEFN [DOCSTRING]).
  1707. ACCESSFN is a symbol.  UPDATEFN is a function or macro which takes
  1708. one more argument than ACCESSFN does.  DEFSETF defines the translation
  1709. of (SETF (ACCESFN . ARGS) NEWVAL) to be a form like (UPDATEFN ARGS... NEWVAL).
  1710. The function UPDATEFN must return its last arg, after performing the
  1711. updating called for."
  1712.   ;; reject ill-formed requests.  too bad one can't test for functionp
  1713.   ;; or macrop.
  1714.   (when (not (symbolp accessfn))
  1715.     (error "First argument of `defsetf' must be a symbol, not `%s'"
  1716.            (prin1-to-string accessfn)))
  1717.   ;; Update properties, when expansion is run.
  1718.   (list 'progn
  1719.     (list 'put (list 'quote accessfn) '':setf-update-fn
  1720.           (list 'quote updatefn))
  1721.     (list 'put (list 'quote accessfn) '':setf-update-doc docstring)))
  1722.  
  1723. ;;; This section provides the "default" setfs for Common-Emacs-Lisp
  1724. ;;; The user will not normally add anything to this, although
  1725. ;;; defstruct will introduce new ones as a matter of fact.
  1726. ;;;
  1727. ;;; Apply is a special case.   The Common Lisp
  1728. ;;; standard makes the case of apply be useful when the user writes
  1729. ;;; something like (apply #'name ...), Emacs Lisp doesn't have the #
  1730. ;;; stuff, but it has (function ...).  Notice that V18 includes a new
  1731. ;;; apply: this file is compatible with V18 and pre-V18 Emacses.
  1732.  
  1733. ;;; INCOMPATIBILITY: the SETF macro evaluates its arguments in the
  1734. ;;; (correct) left to right sequence *before* checking for apply
  1735. ;;; methods (which should really be an special case inside setf).  Due
  1736. ;;; to this, the lambda expression defsetf'd to apply will succeed in
  1737. ;;; applying the right function even if the name was not quoted, but
  1738. ;;; computed!  That extension is not Common Lisp (nor is particularly
  1739. ;;; useful, I think).
  1740.  
  1741. (defsetf apply
  1742.   (lambda (&rest args)
  1743.     ;; dissasemble the calling form
  1744.     ;; "(((quote fn) x1 x2 ... xn) val)" (function instead of quote, too)
  1745.     (let* ((fnform (car args))          ;functional form
  1746.            (applyargs (append           ;arguments "to apply fnform"
  1747.                        (apply 'list* (butlast (cdr args)))
  1748.                        (last args)))
  1749.            (newupdater nil))            ; its update-fn, if any
  1750.       (cond
  1751.        ((and (symbolp fnform)
  1752.              (setq newupdater (get fnform :setf-update-fn)))
  1753.         ;; just do it
  1754.         (apply  newupdater applyargs))
  1755.        (t
  1756.         (error "Can't `setf' to `%s'"
  1757.                (prin1-to-string fnform))))))
  1758.   "`apply' is a special case for `setf'")
  1759.  
  1760.  
  1761. (defsetf aref
  1762.   aset
  1763.   "`setf' inversion for `aref'")
  1764.  
  1765. (defsetf nth
  1766.   setnth
  1767.   "`setf' inversion for `nth'")
  1768.  
  1769. (defsetf nthcdr
  1770.   setnthcdr
  1771.   "`setf' inversion for `nthcdr'")
  1772.  
  1773. (defsetf elt
  1774.   setelt
  1775.   "`setf' inversion for `elt'")
  1776.  
  1777. (defsetf first
  1778.   (lambda (list val) (setnth 0 list val))
  1779.   "`setf' inversion for `first'")
  1780.  
  1781. (defsetf second
  1782.   (lambda (list val) (setnth 1 list val))
  1783.   "`setf' inversion for `second'")
  1784.  
  1785. (defsetf third
  1786.   (lambda (list val) (setnth 2 list val))
  1787.   "`setf' inversion for `third'")
  1788.  
  1789. (defsetf fourth
  1790.   (lambda (list val) (setnth 3 list val))
  1791.   "`setf' inversion for `fourth'")
  1792.  
  1793. (defsetf fifth
  1794.   (lambda (list val) (setnth 4 list val))
  1795.   "`setf' inversion for `fifth'")
  1796.  
  1797. (defsetf sixth
  1798.   (lambda (list val) (setnth 5 list val))
  1799.   "`setf' inversion for `sixth'")
  1800.  
  1801. (defsetf seventh
  1802.   (lambda (list val) (setnth 6 list val))
  1803.   "`setf' inversion for `seventh'")
  1804.  
  1805. (defsetf eighth
  1806.   (lambda (list val) (setnth 7 list val))
  1807.   "`setf' inversion for `eighth'")
  1808.  
  1809. (defsetf ninth
  1810.   (lambda (list val) (setnth 8 list val))
  1811.   "`setf' inversion for `ninth'")
  1812.  
  1813. (defsetf tenth
  1814.   (lambda (list val) (setnth 9 list val))
  1815.   "`setf' inversion for `tenth'")
  1816.  
  1817. (defsetf rest
  1818.   (lambda (list val) (setcdr list val))
  1819.   "`setf' inversion for `rest'")
  1820.  
  1821. (defsetf car setcar "Replace the car of a cons")
  1822.  
  1823. (defsetf cdr setcdr "Replace the cdr of a cons")
  1824.  
  1825. (defsetf caar
  1826.   (lambda (list val) (setcar (nth 0 list) val))
  1827.   "`setf' inversion for `caar'")
  1828.  
  1829. (defsetf cadr
  1830.   (lambda (list val) (setcar (cdr list) val))
  1831.   "`setf' inversion for `cadr'")
  1832.  
  1833. (defsetf cdar
  1834.   (lambda (list val) (setcdr (car list) val))
  1835.   "`setf' inversion for `cdar'")
  1836.  
  1837. (defsetf cddr
  1838.   (lambda (list val) (setcdr (cdr list) val))
  1839.   "`setf' inversion for `cddr'")
  1840.  
  1841. (defsetf caaar
  1842.   (lambda (list val) (setcar (caar list) val))
  1843.   "`setf' inversion for `caaar'")
  1844.  
  1845. (defsetf caadr
  1846.   (lambda (list val) (setcar (cadr list) val))
  1847.   "`setf' inversion for `caadr'")
  1848.  
  1849. (defsetf cadar
  1850.   (lambda (list val) (setcar (cdar list) val))
  1851.   "`setf' inversion for `cadar'")
  1852.  
  1853. (defsetf cdaar
  1854.   (lambda (list val) (setcdr (caar list) val))
  1855.   "`setf' inversion for `cdaar'")
  1856.  
  1857. (defsetf caddr
  1858.   (lambda (list val) (setcar (cddr list) val))
  1859.   "`setf' inversion for `caddr'")
  1860.  
  1861. (defsetf cdadr
  1862.   (lambda (list val) (setcdr (cadr list) val))
  1863.   "`setf' inversion for `cdadr'")
  1864.  
  1865. (defsetf cddar
  1866.   (lambda (list val) (setcdr (cdar list) val))
  1867.   "`setf' inversion for `cddar'")
  1868.  
  1869. (defsetf cdddr
  1870.   (lambda (list val) (setcdr (cddr list) val))
  1871.   "`setf' inversion for `cdddr'")
  1872.  
  1873. (defsetf caaaar
  1874.   (lambda (list val) (setcar (caaar list) val))
  1875.   "`setf' inversion for `caaaar'")
  1876.  
  1877. (defsetf caaadr
  1878.   (lambda (list val) (setcar (caadr list) val))
  1879.   "`setf' inversion for `caaadr'")
  1880.  
  1881. (defsetf caadar
  1882.   (lambda (list val) (setcar (cadar list) val))
  1883.   "`setf' inversion for `caadar'")
  1884.  
  1885. (defsetf cadaar
  1886.   (lambda (list val) (setcar (cdaar list) val))
  1887.   "`setf' inversion for `cadaar'")
  1888.  
  1889. (defsetf cdaaar
  1890.   (lambda (list val) (setcdr (caar list) val))
  1891.   "`setf' inversion for `cdaaar'")
  1892.  
  1893. (defsetf caaddr
  1894.   (lambda (list val) (setcar (caddr list) val))
  1895.   "`setf' inversion for `caaddr'")
  1896.  
  1897. (defsetf cadadr
  1898.   (lambda (list val) (setcar (cdadr list) val))
  1899.   "`setf' inversion for `cadadr'")
  1900.  
  1901. (defsetf cdaadr
  1902.   (lambda (list val) (setcdr (caadr list) val))
  1903.   "`setf' inversion for `cdaadr'")
  1904.  
  1905. (defsetf caddar
  1906.   (lambda (list val) (setcar (cddar list) val))
  1907.   "`setf' inversion for `caddar'")
  1908.  
  1909. (defsetf cdadar
  1910.   (lambda (list val) (setcdr (cadar list) val))
  1911.   "`setf' inversion for `cdadar'")
  1912.  
  1913. (defsetf cddaar
  1914.   (lambda (list val) (setcdr (cdaar list) val))
  1915.   "`setf' inversion for `cddaar'")
  1916.  
  1917. (defsetf cadddr
  1918.   (lambda (list val) (setcar (cdddr list) val))
  1919.   "`setf' inversion for `cadddr'")
  1920.  
  1921. (defsetf cddadr
  1922.   (lambda (list val) (setcdr (cdadr list) val))
  1923.   "`setf' inversion for `cddadr'")
  1924.  
  1925. (defsetf cdaddr
  1926.   (lambda (list val) (setcdr (caddr list) val))
  1927.   "`setf' inversion for `cdaddr'")
  1928.  
  1929. (defsetf cdddar
  1930.   (lambda (list val) (setcdr (cddar list) val))
  1931.   "`setf' inversion for `cdddar'")
  1932.  
  1933. (defsetf cddddr
  1934.   (lambda (list val) (setcdr (cddr list) val))
  1935.   "`setf' inversion for `cddddr'")
  1936.  
  1937.  
  1938. (defsetf get
  1939.   put
  1940.   "`setf' inversion for `get' is `put'")
  1941.  
  1942. (defsetf symbol-function
  1943.   fset
  1944.   "`setf' inversion for `symbol-function' is `fset'")
  1945.  
  1946. (defsetf symbol-plist
  1947.   setplist
  1948.   "`setf' inversion for `symbol-plist' is `setplist'")
  1949.  
  1950. (defsetf symbol-value
  1951.   set
  1952.   "`setf' inversion for `symbol-value' is `set'")
  1953.  
  1954. ;;; Modify macros
  1955. ;;;
  1956. ;;; It could be nice to implement define-modify-macro, but I don't
  1957. ;;; think it really pays.
  1958.  
  1959. (defmacro incf (ref &optional delta)
  1960.   "(incf REF [DELTA]) -> increment the g.v. REF by DELTA (default 1)"
  1961.   (if (null delta)
  1962.       (setq delta 1))
  1963.   (list 'setf ref (list '+ ref delta)))
  1964.  
  1965. (defmacro decf (ref &optional delta)
  1966.   "(decf REF [DELTA]) -> decrement the g.v. REF by DELTA (default 1)"
  1967.   (if (null delta)
  1968.       (setq delta 1))
  1969.   (list 'setf ref (list '- ref delta)))
  1970.  
  1971. (defmacro push (item ref)
  1972.   "(push ITEM REF) -> cons ITEM at the head of the g.v. REF (a list)"
  1973.   (list 'setf ref (list 'cons item ref)))
  1974.  
  1975. (defmacro pushnew (item ref)
  1976.   "(pushnew ITEM REF): adjoin ITEM at the head of the g.v. REF (a list)"
  1977.   (list 'setf ref (list 'adjoin item ref)))
  1978.  
  1979. (defmacro pop (ref)
  1980.   "(pop REF) -> (prog1 (car REF) (setf REF (cdr REF)))"
  1981.   (let ((listname (gensym)))
  1982.     (list 'let (list (list listname ref))
  1983.           (list 'prog1
  1984.                 (list 'car listname)
  1985.                 (list 'setf ref (list 'cdr listname))))))
  1986.  
  1987. ;;; PSETF
  1988. ;;;
  1989. ;;; Psetf is the generalized variable equivalent of psetq.  The right
  1990. ;;; hand sides are evaluated and assigned (via setf) to the left hand
  1991. ;;; sides. The evaluations are done in an environment where they
  1992. ;;; appear to occur in parallel.
  1993.  
  1994. (defmacro psetf (&rest pairs)
  1995.   "(psetf {PLACE VALUE}...): Set several generalized variables in parallel.
  1996. All the VALUEs are computed, and then all the PLACEs are stored as in `setf'.
  1997. See also `psetq', `shiftf' and `rotatef'."
  1998.   (unless (evenp (length pairs))
  1999.     (error "Odd number of arguments to `psetf'"))
  2000.   (multiple-value-bind
  2001.       (places forms)
  2002.       (unzip-list pairs)
  2003.     ;; obtain fresh symbols to simulate the parallelism
  2004.     (multiple-value-bind
  2005.         (bindings newsyms)
  2006.         (pair-with-newsyms forms)
  2007.       (list 'let
  2008.             bindings
  2009.             (cons 'setf (zip-lists places newsyms))
  2010.             nil))))
  2011.  
  2012. ;;; SHIFTF and ROTATEF 
  2013. ;;;
  2014.  
  2015. (defmacro shiftf (&rest forms)
  2016.   "(shiftf PLACE1 PLACE2... NEWVALUE): set PLACE1 to PLACE2, PLACE2 to PLACE3...
  2017. Each PLACE is set to the old value of the following PLACE,
  2018. and the last PLACE is set to the value NEWVALUE."
  2019.   (unless (> (length forms) 1)
  2020.     (error "`shiftf' needs more than one argument"))
  2021.   (let ((places (butlast forms))
  2022.     (newvalue (car (last forms))))
  2023.     ;; the places are accessed to fresh symbols
  2024.     (multiple-value-bind
  2025.     (bindings newsyms)
  2026.     (pair-with-newsyms places)
  2027.       (list 'let bindings
  2028.         (cons 'setf
  2029.           (zip-lists places
  2030.                  (append (cdr newsyms) (list newvalue))))
  2031.         (car newsyms)))))
  2032.  
  2033. (defmacro rotatef (&rest places)
  2034.   "(rotatef PLACE...) sets each PLACE to the old value of the following PLACE.
  2035. The last PLACE is set to the old value of the first PLACE.
  2036. Thus, the values rotate through the PLACEs."
  2037.   (cond
  2038.    ((null places)
  2039.     nil)
  2040.    (t
  2041.     (multiple-value-bind
  2042.     (bindings newsyms)
  2043.     (pair-with-newsyms places)
  2044.       (list
  2045.        'let bindings
  2046.        (cons 'setf
  2047.          (zip-lists places
  2048.             (append (cdr newsyms) (list (car newsyms)))))
  2049.        nil)))))
  2050.  
  2051. ;;;; STRUCTS
  2052. ;;;;    This file provides the structures mechanism.  See the
  2053. ;;;;    documentation for Common-Lisp's defstruct.  Mine doesn't
  2054. ;;;;    implement all the functionality of the standard, although some
  2055. ;;;;    more could be grafted if so desired.  More details along with
  2056. ;;;;    the code.
  2057. ;;;;
  2058. ;;;;
  2059. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  2060. ;;;;       (quiroz@cs.rochester.edu)
  2061.  
  2062.  
  2063. (defkeyword :include             "Syntax of `defstruct'")
  2064. (defkeyword :named               "Syntax of `defstruct'")
  2065. (defkeyword :conc-name           "Syntax of `defstruct'")
  2066. (defkeyword :copier              "Syntax of `defstruct'")
  2067. (defkeyword :predicate           "Syntax of `defstruct'")
  2068. (defkeyword :print-function      "Syntax of `defstruct'")
  2069. (defkeyword :type                "Syntax of `defstruct'")
  2070. (defkeyword :initial-offset      "Syntax of `defstruct'")
  2071.  
  2072. (defkeyword :structure-doc       "Documentation string for a structure.")
  2073. (defkeyword :structure-slotsn    "Number of slots in structure")
  2074. (defkeyword :structure-slots     "List of the slot's names")
  2075. (defkeyword :structure-indices   "List of (KEYWORD-NAME . INDEX)")
  2076. (defkeyword :structure-initforms "List of (KEYWORD-NAME . INITFORM)")
  2077.  
  2078.  
  2079. (defmacro defstruct (&rest args)
  2080.   "(defstruct NAME [DOC-STRING] . SLOTS)  define NAME as structure type.
  2081. NAME must be a symbol, the name of the new structure.  It could also
  2082. be a list (NAME . OPTIONS), but not all options are supported currently.
  2083. As of Dec. 1986, this is supporting :conc-name, :copier and :predicate
  2084. completely, :include arguably completely and :constructor only to
  2085. change the name of the default constructor.  No BOA constructors allowed.
  2086. The DOC-STRING is established as the 'structure-doc' property of NAME.
  2087. The SLOTS are one or more of the following:
  2088. SYMBOL -- meaning the SYMBOL is the name of a SLOT of NAME
  2089. list of SYMBOL and VALUE -- meaning that VALUE is the initial value of
  2090. the slot.
  2091. `defstruct' defines functions `make-NAME', `NAME-p', `copy-NAME' for the
  2092. structure, and functions with the same name as the slots to access
  2093. them.  `setf' of the accessors sets their values."
  2094.   (multiple-value-bind
  2095.       (name options docstring slotsn slots initlist)
  2096.       (parse$defstruct$args args)
  2097.     ;; Names for the member functions come from the options.  The
  2098.     ;; slots* stuff collects info about the slots declared explicitly. 
  2099.     (multiple-value-bind
  2100.         (conc-name constructor copier predicate moreslotsn moreslots moreinits)
  2101.         (parse$defstruct$options name options slots)
  2102.       ;; The moreslots* stuff refers to slots gained as a consequence
  2103.       ;; of (:include clauses).
  2104.       (when (and (numberp moreslotsn)
  2105.                  (> moreslotsn 0))
  2106.         (setf slotsn (+ slotsn moreslotsn))
  2107.         (setf slots (append moreslots slots))
  2108.         (setf initlist (append moreinits initlist)))
  2109.       (unless (> slotsn 0)
  2110.         (error "%s needs at least one slot"
  2111.                (prin1-to-string name)))
  2112.       (let ((dups (duplicate-symbols-p slots)))
  2113.         (when dups
  2114.           (error "`%s' are duplicates"
  2115.                  (prin1-to-string dups))))
  2116.       (setq initlist (simplify$inits slots initlist))
  2117.       (let (properties functions keywords accessors alterators returned)
  2118.         ;; compute properties of NAME
  2119.         (setq properties
  2120.               (list
  2121.                (list 'put (list 'quote name) :structure-doc
  2122.                      docstring)
  2123.                (list 'put (list 'quote name) :structure-slotsn
  2124.                      slotsn)
  2125.                (list 'put (list 'quote name) :structure-slots
  2126.                      (list 'quote slots))
  2127.                (list 'put (list 'quote name) :structure-initforms
  2128.                      (list 'quote initlist))
  2129.                (list 'put (list 'quote name) :structure-indices
  2130.                      (list 'quote (extract$indices initlist)))))
  2131.  
  2132.         ;; Compute functions associated with NAME.  This is not
  2133.     ;; handling BOA constructors yet, but here would be the place.
  2134.         (setq functions
  2135.               (list
  2136.                (list 'fset (list 'quote constructor)
  2137.                      (list 'function
  2138.                            (list 'lambda (list '&rest 'args)
  2139.                                  (list 'make$structure$instance
  2140.                                        (list 'quote name)
  2141.                                        'args))))
  2142.                (list 'fset (list 'quote copier)
  2143.                      (list 'function
  2144.                            (list 'lambda (list 'struct)
  2145.                                  (list 'copy-vector 'struct))))
  2146.                (list 'fset (list 'quote predicate)
  2147.                      (list 'function
  2148.                            (list 'lambda (list 'thing)
  2149.                                  (list 'and
  2150.                                        (list 'vectorp 'thing)
  2151.                                        (list 'eq
  2152.                                              (list 'elt 'thing 0)
  2153.                                              (list 'quote name))
  2154.                                        (list '=
  2155.                                              (list 'length 'thing)
  2156.                                              (1+ slotsn))))))))
  2157.         ;; compute accessors for NAME's slots
  2158.         (multiple-value-setq
  2159.             (accessors alterators keywords)
  2160.             (build$accessors$for name conc-name predicate slots slotsn))
  2161.         ;; generate returned value -- not defined by the standard
  2162.         (setq returned
  2163.               (list
  2164.                (cons 'vector
  2165.                      (mapcar
  2166.                       '(lambda (x) (list 'quote x))
  2167.                       (cons name slots)))))
  2168.         ;; generate code
  2169.         (cons 'progn
  2170.               (nconc properties functions keywords
  2171.                      accessors alterators returned))))))
  2172.  
  2173. (defun parse$defstruct$args (args)
  2174.   "PARSE$DEFSTRUCT$ARGS ARGS => NAME OPTIONS DOCSTRING SLOTSN SLOTS INITLIST
  2175. NAME=symbol, OPTIONS=list of, DOCSTRING=string, SLOTSN=count of slots,
  2176. SLOTS=list of their names, INITLIST=alist (keyword . initform)."
  2177.   (let (name                            ;args=(symbol...) or ((symbol...)...)
  2178.         options                         ;args=((symbol . options) ...)
  2179.         (docstring "")                  ;args=(head docstring . slotargs)
  2180.         slotargs                        ;second or third cdr of args
  2181.         (slotsn 0)                      ;number of slots 
  2182.         (slots '())                     ;list of slot names
  2183.         (initlist '()))                 ;list of (slot keyword . initform)
  2184.     ;; extract name and options
  2185.     (cond
  2186.      ((symbolp (car args))              ;simple name
  2187.       (setq name    (car args)
  2188.             options '()))
  2189.      ((and (listp   (car args))         ;(name . options)
  2190.            (symbolp (caar args)))
  2191.       (setq name    (caar args)
  2192.             options (cdar args)))
  2193.      (t
  2194.       (error "First arg to `defstruct' must be symbol or (symbol ...)")))
  2195.     (setq slotargs (cdr args))
  2196.     ;; is there a docstring?
  2197.     (when (stringp (car slotargs))
  2198.       (setq docstring (car slotargs)
  2199.             slotargs  (cdr slotargs)))
  2200.     ;; now for the slots
  2201.     (multiple-value-bind
  2202.         (slotsn slots initlist)
  2203.         (process$slots slotargs)
  2204.       (values name options docstring slotsn slots initlist))))
  2205.  
  2206. (defun process$slots (slots)
  2207.   "PROCESS$SLOTS SLOTS => SLOTSN SLOTSLIST INITLIST
  2208. Converts a list of symbols or lists of symbol and form into the last 3
  2209. values returned by PARSE$DEFSTRUCT$ARGS."
  2210.   (let ((slotsn (length slots))         ;number of slots
  2211.         slotslist                       ;(slot1 slot2 ...)
  2212.         initlist)                       ;((:slot1 . init1) ...)
  2213.     (do*
  2214.         ((ptr  slots     (cdr ptr))
  2215.          (this (car ptr) (car ptr)))
  2216.         ((endp ptr))
  2217.       (cond
  2218.        ((symbolp this)
  2219.         (setq slotslist (cons this slotslist))
  2220.         (setq initlist (acons (keyword-of this) nil initlist)))
  2221.        ((and (listp this)
  2222.              (symbolp (car this)))
  2223.         (let ((name (car this))
  2224.               (form (cadr this)))
  2225.           ;; this silently ignores any slot options.  bad...
  2226.           (setq slotslist (cons name slotslist))
  2227.           (setq initlist  (acons (keyword-of name) form initlist))))
  2228.        (t
  2229.         (error "Slot should be symbol or (symbol ...), not `%s'"
  2230.                (prin1-to-string this)))))
  2231.     (values slotsn (nreverse slotslist) (nreverse initlist))))
  2232.  
  2233. (defun parse$defstruct$options (name options slots)
  2234.   "PARSE$DEFSTRUCT$OPTIONS NAME OPTIONS SLOTS => CONC-NAME CONST COPIER PRED
  2235. Returns at least those 4 values (a string and 3 symbols, to name the necessary
  2236. functions),  might return also things discovered by actually
  2237. inspecting the options, namely MORESLOTSN MORESLOTS MOREINITS, as can
  2238. be created by :include, and perhaps a list of BOACONSTRUCTORS."
  2239.   (let* ((namestring (symbol-name name))
  2240.          ;; to build the return values
  2241.          (conc-name  (concat namestring "-"))
  2242.          (const (intern (concat "make-" namestring)))
  2243.          (copier (intern (concat "copy-" namestring)))
  2244.          (pred (intern (concat namestring "-p")))
  2245.          (moreslotsn 0)
  2246.          (moreslots '())
  2247.          (moreinits '())
  2248.          ;; auxiliaries
  2249.          option-head                    ;When an option is not a plain
  2250.          option-second                  ; keyword, it must be a list of
  2251.          option-rest                    ; the form (head second . rest)
  2252.          these-slotsn                   ;When :include is found, the
  2253.          these-slots                    ; info about the included
  2254.          these-inits                    ; structure is added here.
  2255.          )
  2256.     ;; Values above are the defaults.  Now we read the options themselves
  2257.     (dolist (option options)
  2258.       ;; 2 cases arise, as options must be a keyword or a list
  2259.       (cond
  2260.        ((keywordp option)
  2261.         (case option
  2262.           (:named
  2263.            )                            ;ignore silently
  2264.           (t
  2265.            (error "Can't recognize option `%s'"
  2266.                   (prin1-to-string option)))))
  2267.        ((and (listp option)
  2268.              (keywordp (setq option-head (car option))))
  2269.         (setq option-second (second option))
  2270.         (setq option-rest   (nthcdr 2 option))
  2271.         (case option-head
  2272.           (:conc-name
  2273.            (setq conc-name
  2274.                  (cond
  2275.                   ((stringp option-second)
  2276.                    option-second)
  2277.                   ((null option-second)
  2278.                    "")
  2279.                   (t
  2280.                    (error "`%s' is invalid as `conc-name'"
  2281.                           (prin1-to-string option-second))))))
  2282.           (:copier
  2283.            (setq copier
  2284.                  (cond
  2285.                   ((and (symbolp option-second)
  2286.                         (null option-rest))
  2287.                    option-second)
  2288.                   (t
  2289.                    (error "Can't recognize option `%s'"
  2290.                           (prin1-to-string option))))))
  2291.  
  2292.           (:constructor                 ;no BOA-constructors allowed
  2293.            (setq const
  2294.                  (cond
  2295.                   ((and (symbolp option-second)
  2296.                         (null option-rest))
  2297.                    option-second)
  2298.                   (t
  2299.                    (error "Can't recognize option `%s'"
  2300.                           (prin1-to-string option))))))
  2301.           (:predicate
  2302.            (setq pred
  2303.                  (cond
  2304.                   ((and (symbolp option-second)
  2305.                         (null option-rest))
  2306.                    option-second)
  2307.                   (t
  2308.                    (error "Can't recognize option `%s'"
  2309.                           (prin1-to-string option))))))
  2310.           (:include
  2311.            (unless (symbolp option-second)
  2312.              (error "Arg to `:include' should be a symbol, not `%s'"
  2313.                     (prin1-to-string option-second)))
  2314.            (setq these-slotsn (get option-second :structure-slotsn)
  2315.                  these-slots  (get option-second :structure-slots)
  2316.                  these-inits  (get option-second :structure-initforms))
  2317.            (unless (and (numberp these-slotsn)
  2318.                         (> these-slotsn 0))
  2319.              (error "`%s' is not a valid structure"
  2320.                     (prin1-to-string option-second)))
  2321.            (multiple-value-bind
  2322.                (xtra-slotsn xtra-slots xtra-inits)
  2323.                (process$slots option-rest)
  2324.              (when (> xtra-slotsn 0)
  2325.                (dolist (xslot xtra-slots)
  2326.                  (unless (memq xslot these-slots)
  2327.                    (error "`%s' is not a slot of `%s'"
  2328.                           (prin1-to-string xslot)
  2329.                           (prin1-to-string option-second))))
  2330.                (setq these-inits (append xtra-inits these-inits)))
  2331.              (setq moreslotsn (+ moreslotsn these-slotsn))
  2332.              (setq moreslots  (append these-slots moreslots))
  2333.              (setq moreinits  (append these-inits moreinits))))
  2334.           ((:print-function :type :initial-offset)
  2335.            )                            ;ignore silently
  2336.           (t
  2337.            (error "Can't recognize option `%s'"
  2338.                   (prin1-to-string option)))))
  2339.        (t
  2340.         (error "Can't recognize option `%s'"
  2341.                (prin1-to-string option)))))
  2342.     ;; Return values found
  2343.     (values conc-name const copier pred
  2344.             moreslotsn moreslots moreinits)))
  2345.  
  2346. (defun simplify$inits (slots initlist)
  2347.   "SIMPLIFY$INITS SLOTS INITLIST => new INITLIST
  2348. Removes from INITLIST - an ALIST - any shadowed bindings."
  2349.   (let ((result '())                    ;built here
  2350.         key                             ;from the slot 
  2351.         )
  2352.     (dolist (slot slots)
  2353.       (setq key (keyword-of slot))
  2354.       (setq result (acons key (cdr (assoc key initlist)) result)))
  2355.     (nreverse result)))
  2356.  
  2357. (defun extract$indices (initlist)
  2358.   "EXTRACT$INDICES INITLIST => indices list
  2359. Kludge.  From a list of pairs (keyword . form) build a list of pairs
  2360. of the form (keyword . position in list from 0).  Useful to precompute
  2361. some of the work of MAKE$STRUCTURE$INSTANCE."
  2362.   (let ((result '())
  2363.         (index   0))
  2364.     (dolist (entry initlist (nreverse result))
  2365.       (setq result (acons (car entry) index result)
  2366.             index  (+ index 1)))))
  2367.  
  2368. (defun build$accessors$for (name conc-name predicate slots slotsn)
  2369.   "BUILD$ACCESSORS$FOR NAME PREDICATE SLOTS SLOTSN  => FSETS DEFSETFS KWDS
  2370. Generate the code for accesors and defsetfs of a structure called
  2371. NAME, whose slots are SLOTS.  Also, establishes the keywords for the
  2372. slots names."
  2373.   (do ((i 0 (1+ i))
  2374.        (accessors '())
  2375.        (alterators '())
  2376.        (keywords '())
  2377.        (canonic  ""))                   ;slot name with conc-name prepended
  2378.       ((>= i slotsn)
  2379.        (values
  2380.         (nreverse accessors) (nreverse alterators) (nreverse keywords)))
  2381.     (setq canonic (intern (concat conc-name (symbol-name (nth i slots)))))
  2382.     (setq accessors
  2383.           (cons
  2384.            (list 'fset (list 'quote canonic)
  2385.                  (list 'function
  2386.                        (list 'lambda (list 'object)
  2387.                              (list 'cond
  2388.                                    (list (list predicate 'object)
  2389.                                          (list 'aref 'object (1+ i)))
  2390.                                    (list 't
  2391.                                          (list 'error
  2392.                                                "`%s' not a %s."
  2393.                                                (list 'prin1-to-string
  2394.                                                      'object)
  2395.                                                (list 'prin1-to-string
  2396.                                                      (list 'quote
  2397.                                                            name))))))))
  2398.            accessors))
  2399.     (setq alterators
  2400.            (cons
  2401.             (list 'defsetf canonic
  2402.                   (list 'lambda (list 'object 'newval)
  2403.                         (list 'cond
  2404.                               (list (list predicate 'object)
  2405.                                     (list 'aset 'object (1+ i) 'newval))
  2406.                               (list 't
  2407.                                     (list 'error
  2408.                                           "`%s' not a `%s'"
  2409.                                           (list 'prin1-to-string
  2410.                                                 'object)
  2411.                                           (list 'prin1-to-string
  2412.                                                 (list 'quote
  2413.                                                       name)))))))
  2414.             alterators))
  2415.     (setq keywords
  2416.           (cons (list 'defkeyword (keyword-of (nth i slots)))
  2417.                 keywords))))
  2418.  
  2419. (defun make$structure$instance (name args)
  2420.   "MAKE$STRUCTURE$INSTANCE NAME ARGS => new struct NAME
  2421. A struct of type NAME is created, some slots might be initialized
  2422. according to ARGS (the &rest argument of MAKE-name)."
  2423.   (unless (symbolp name)
  2424.     (error "`%s' is not a possible name for a structure"
  2425.            (prin1-to-string name)))
  2426.   (let ((initforms (get name :structure-initforms))
  2427.         (slotsn    (get name :structure-slotsn))
  2428.         (indices   (get name :structure-indices))
  2429.         initalist                       ;pairlis'd on initforms
  2430.         initializers                    ;definitive initializers
  2431.         )
  2432.     ;; check sanity of the request
  2433.     (unless (and (numberp slotsn)
  2434.                  (> slotsn 0))
  2435.       (error "`%s' is not a defined structure"
  2436.              (prin1-to-string name)))
  2437.     (unless (evenp (length args))
  2438.       (error "Slot initializers `%s' not of even length"
  2439.              (prin1-to-string args)))
  2440.     ;; analyze the initializers provided by the call
  2441.     (multiple-value-bind
  2442.         (speckwds specvals)             ;keywords and values given 
  2443.         (unzip-list args)               ; by the user
  2444.       ;; check that all the arguments are introduced by keywords 
  2445.       (unless (every (function keywordp) speckwds)
  2446.         (error "All of the names in `%s' should be keywords"
  2447.                (prin1-to-string speckwds)))
  2448.       ;; check that all the keywords are known
  2449.       (dolist (kwd speckwds)
  2450.         (unless (numberp (cdr (assoc kwd indices)))
  2451.           (error "`%s' is not a valid slot name for %s"
  2452.                  (prin1-to-string kwd) (prin1-to-string name))))
  2453.       ;; update initforms
  2454.       (setq initalist
  2455.             (pairlis speckwds
  2456.                      (do* ;;protect values from further evaluation
  2457.                          ((ptr specvals (cdr ptr))
  2458.                           (val (car ptr) (car ptr))
  2459.                           (result '()))
  2460.                          ((endp ptr) (nreverse result))
  2461.                        (setq result
  2462.                              (cons (list 'quote val)
  2463.                                    result)))
  2464.                      (copy-sequence initforms)))
  2465.       ;; compute definitive initializers
  2466.       (setq initializers
  2467.             (do* ;;gather the values of the most definitive forms
  2468.                 ((ptr indices (cdr ptr))
  2469.                  (key (caar ptr) (caar ptr))
  2470.                  (result '()))
  2471.                 ((endp ptr) (nreverse result))
  2472.               (setq result
  2473.                     (cons (eval (cdr (assoc key initalist))) result))))
  2474.       ;; do real initialization
  2475.       (apply (function vector)
  2476.              (cons name initializers)))))
  2477.  
  2478. ;;;; end of cl-structs.el
  2479.  
  2480. ;;;; end of cl.el
  2481.