home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / elisp / packages / cl.el < prev    next >
Encoding:
Text File  |  1993-02-25  |  120.7 KB  |  3,166 lines

  1. ;; Common-Lisp extensions for GNU Emacs Lisp.
  2. ;; Copyright (C) 1987, 1988, 1989, 1992  Free Software Foundation, Inc.
  3.  
  4. ;; Author: Cesar Quiroz <quiroz@cs.rochester.edu>
  5. ;; Keywords: extensions
  6.  
  7. ;; LCD Archive Entry:
  8. ;; cl|Cesar Quiroz|quiroz@cs.rochester.edu|
  9. ;; Common-Lisp extensions for GNU Emacs Lisp.|
  10. ;; 07-02-1993|3.0|~/packages/cl.el.Z|
  11.  
  12. (defvar cl-version "3.0    07-February-1993")
  13.  
  14. ;; This file is part of GNU Emacs.
  15.  
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY.  No author or distributor
  18. ;; accepts responsibility to anyone for the consequences of using it
  19. ;; or for whether it serves any particular purpose or works at all,
  20. ;; unless he says so in writing.  Refer to the GNU Emacs General Public
  21. ;; License for full details.
  22.  
  23. ;; Everyone is granted permission to copy, modify and redistribute
  24. ;; GNU Emacs, but only under the conditions described in the
  25. ;; GNU Emacs General Public License.   A copy of this license is
  26. ;; supposed to have been given to you along with GNU Emacs so you
  27. ;; can know your rights and responsibilities.  It should be in a
  28. ;; file named COPYING.  Among other things, the copyright notice
  29. ;; and this notice must be preserved on all copies.
  30.  
  31. ;;; Notes from Rob Austein on his mods
  32. ;; yaya:/usr/u/sra/cl/cl.el, 5-May-1991 16:01:34, sra
  33. ;;
  34. ;; Slightly hacked copy of cl.el 2.0 beta 27.
  35. ;;
  36. ;; Various minor performance improvements:
  37. ;;  a) Don't use MAPCAR when we're going to discard its results.
  38. ;;  b) Make various macros a little more clever about optimizing
  39. ;;     generated code in common cases.
  40. ;;  c) Fix DEFSETF to expand to the right code at compile-time.
  41. ;;  d) Make various macros cleverer about generating reasonable
  42. ;;     code when compiled, particularly forms like DEFSTRUCT which
  43. ;;     are usually used at top-level and thus are only compiled if
  44. ;;     you use Hallvard Furuseth's hacked bytecomp.el.
  45. ;;
  46. ;; New features: GETF, REMF, and REMPROP.
  47. ;;
  48. ;; Notes:
  49. ;;  1) I'm sceptical about the FBOUNDP checks in SETF.  Why should
  50. ;;     the SETF expansion fail because the SETF method isn't defined
  51. ;;     at compile time?  Lisp is going to check for a binding at run-time
  52. ;;     anyway, so maybe we should just assume the user's right here.
  53.  
  54. ;;; Commentary:
  55.  
  56. ;;;; These are extensions to Emacs Lisp that provide some form of
  57. ;;;; Common Lisp compatibility, beyond what is already built-in
  58. ;;;; in Emacs Lisp.
  59. ;;;;
  60. ;;;; When developing them, I had the code spread among several files.
  61. ;;;; This file 'cl.el' is a concatenation of those original files,
  62. ;;;; minus some declarations that became redundant.  The marks between
  63. ;;;; the original files can be found easily, as they are lines that
  64. ;;;; begin with four semicolons (as this does).  The names of the
  65. ;;;; original parts follow the four semicolons in uppercase, those
  66. ;;;; names are GLOBAL, SYMBOLS, LISTS, SEQUENCES, CONDITIONALS,
  67. ;;;; ITERATIONS, MULTIPLE VALUES, ARITH, SETF and DEFSTRUCT.  If you
  68. ;;;; add functions to this file, you might want to put them in a place
  69. ;;;; that is compatible with the division above (or invent your own
  70. ;;;; categories).
  71. ;;;;
  72. ;;;; To compile this file, make sure you load it first.  This is
  73. ;;;; because many things are implemented as macros and now that all
  74. ;;;; the files are concatenated together one cannot ensure that
  75. ;;;; declaration always precedes use.
  76. ;;;;
  77. ;;;; Bug reports, suggestions and comments,
  78. ;;;; to quiroz@cs.rochester.edu
  79.  
  80.  
  81. ;;;; GLOBAL
  82. ;;;;    This file provides utilities and declarations that are global
  83. ;;;;    to Common Lisp and so might be used by more than one of the
  84. ;;;;    other libraries.  Especially, I intend to keep here some
  85. ;;;;    utilities that help parsing/destructuring some difficult calls. 
  86. ;;;;
  87. ;;;;
  88. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  89. ;;;;       (quiroz@cs.rochester.edu)
  90.  
  91. ;;; Too many pieces of the rest of this package use psetq.  So it is unwise to
  92. ;;; use here anything but plain Emacs Lisp!  There is a neater recursive form
  93. ;;; for the algorithm that deals with the bodies.
  94.  
  95. ;;; Code:
  96.  
  97. ;;; This version is due to Hallvard Furuseth (hallvard@ifi.uio.no, 6 Jul 91)
  98. (defmacro psetq (&rest args)
  99.   "(psetq {VARIABLE VALUE}...): In parallel, set each VARIABLE to its VALUE.
  100. All the VALUEs are evaluated, and then all the VARIABLEs are set.
  101. Aside from order of evaluation, this is the same as `setq'."
  102.   ;; check there is a reasonable number of forms
  103.   (if (/= (% (length args) 2) 0)
  104.       (error "Odd number of arguments to `psetq'"))
  105.   (setq args (copy-sequence args))      ;for safety below
  106.   (prog1 (cons 'setq args)
  107.     (while (progn (if (not (symbolp (car args)))
  108.               (error "`psetq' expected a symbol, found '%s'."
  109.                  (prin1-to-string (car args))))
  110.           (cdr (cdr args)))
  111.       (setcdr args (list (list 'prog1 (nth 1 args)
  112.                    (cons 'setq
  113.                      (setq args (cdr (cdr args))))))))))
  114.  
  115. ;;; utilities
  116. ;;;
  117. ;;; pair-with-newsyms takes a list and returns a list of lists of the
  118. ;;; form (newsym form), such that a let* can then bind the evaluation
  119. ;;; of the forms to the newsyms.  The idea is to guarantee correct
  120. ;;; order of evaluation of the subforms of a setf.  It also returns a
  121. ;;; list of the newsyms generated, in the corresponding order.
  122.  
  123. (defun pair-with-newsyms (oldforms)
  124.   "PAIR-WITH-NEWSYMS OLDFORMS
  125. The top-level components of the list oldforms are paired with fresh
  126. symbols, the pairings list and the newsyms list are returned."
  127.   (do ((ptr oldforms (cdr ptr))
  128.        (bindings '())
  129.        (newsyms  '()))
  130.       ((endp ptr) (values (nreverse bindings) (nreverse newsyms)))
  131.     (let ((newsym (gentemp)))
  132.       (setq bindings (cons (list newsym (car ptr)) bindings))
  133.       (setq newsyms  (cons newsym newsyms)))))
  134.  
  135. (defun zip-lists (evens odds)
  136.   "Merge two lists EVENS and ODDS, taking elts from each list alternatingly.
  137. EVENS and ODDS are two lists.  ZIP-LISTS constructs a new list, whose
  138. even numbered elements (0,2,...) come from EVENS and whose odd
  139. numbered elements (1,3,...) come from ODDS. 
  140. The construction stops when the shorter list is exhausted."
  141.   (do* ((p0   evens    (cdr p0))
  142.         (p1   odds     (cdr p1))
  143.         (even (car p0) (car p0))
  144.         (odd  (car p1) (car p1))
  145.         (result '()))
  146.       ((or (endp p0) (endp p1))
  147.        (nreverse result))
  148.     (setq result
  149.           (cons odd (cons even result)))))
  150.  
  151. (defun unzip-list (list)
  152.   "Extract even and odd elements of LIST into two separate lists.
  153. The argument LIST is separated in two strands, the even and the odd
  154. numbered elements.  Numbering starts with 0, so the first element
  155. belongs in EVENS. No check is made that there is an even number of
  156. elements to start with."
  157.   (do* ((ptr   list       (cddr ptr))
  158.         (this  (car ptr)  (car ptr))
  159.         (next  (cadr ptr) (cadr ptr))
  160.         (evens '())
  161.         (odds  '()))
  162.       ((endp ptr)
  163.        (values (nreverse evens) (nreverse odds)))
  164.     (setq evens (cons this evens))
  165.     (setq odds  (cons next odds))))
  166.  
  167. (defun reassemble-argslists (argslists)
  168.   "(reassemble-argslists ARGSLISTS) => a list of lists
  169. ARGSLISTS is a list of sequences.  Return a list of lists, the first
  170. sublist being all the entries coming from ELT 0 of the original
  171. sublists, the next those coming from ELT 1 and so on, until the
  172. shortest list is exhausted."
  173.   (let* ((minlen   (apply 'min (mapcar 'length argslists)))
  174.          (result   '()))
  175.     (dotimes (i minlen (nreverse result))
  176.       ;; capture all the elements at index i
  177.       (setq result
  178.             (cons (mapcar (function (lambda (sublist) (elt sublist i)))
  179.                    argslists)
  180.                   result)))))
  181.  
  182.  
  183. ;;; Checking that a list of symbols contains no duplicates is a common
  184. ;;; task when checking the legality of some macros.  The check for 'eq
  185. ;;; pairs can be too expensive, as it is quadratic on the length of
  186. ;;; the list.  I use a 4-pass, linear, counting approach.  It surely
  187. ;;; loses on small lists (less than 5 elements?), but should win for
  188. ;;; larger lists.  The fourth pass could be eliminated.
  189. ;;; 10 dec 1986.  Emacs Lisp has no REMPROP, so I just eliminated the
  190. ;;; 4th pass.
  191. ;;;
  192. ;;; [22 April 1991, sra] REMPROP now in library, so restored 4th pass.
  193. (defun duplicate-symbols-p (list)
  194.   "Find all symbols appearing more than once in LIST.
  195. Return a list of all such duplicates; `nil' if there are no duplicates."
  196.   (let  ((duplicates '())               ;result built here
  197.          (propname   (gensym))          ;we use a fresh property
  198.          )
  199.     ;; check validity
  200.     (unless (and (listp list)
  201.                  (every 'symbolp list))
  202.       (error "a list of symbols is needed"))
  203.     ;; pass 1: mark
  204.     (dolist (x list)
  205.       (put x propname 0))
  206.     ;; pass 2: count
  207.     (dolist (x list)
  208.       (put x propname (1+ (get x propname))))
  209.     ;; pass 3: collect
  210.     (dolist (x list)
  211.       (if (> (get x propname) 1)
  212.           (setq duplicates (cons x duplicates))))
  213.     ;; pass 4: unmark.
  214.     (dolist (x list)
  215.       (remprop x propname))
  216.     ;; return result
  217.     duplicates))
  218.  
  219. ;;;; end of cl-global.el
  220.  
  221. ;;;; SYMBOLS
  222. ;;;;    This file provides the gentemp function, which generates fresh
  223. ;;;;    symbols, plus some other minor Common Lisp symbol tools.
  224. ;;;;
  225. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  226. ;;;;       (quiroz@cs.rochester.edu)
  227.  
  228. ;;; Keywords.  There are no packages in Emacs Lisp, so this is only a
  229. ;;; kludge around to let things be "as if" a keyword package was around.
  230.  
  231. (defmacro defkeyword (x &optional docstring)
  232.   "Make symbol X a keyword (symbol whose value is itself).
  233. Optional second argument is a documentation string for it."
  234.   (cond ((symbolp x)
  235.          (list 'defconst x (list 'quote x) docstring))
  236.         (t
  237.          (error "`%s' is not a symbol" (prin1-to-string x)))))
  238.  
  239. (defun keywordp (sym)
  240.   "t if SYM is a keyword."
  241.   (if (and (symbolp sym) (char-equal (aref (symbol-name sym) 0) ?\:))
  242.       ;; looks like one, make sure value is right
  243.       (set sym sym)
  244.     nil))
  245.  
  246. (defun keyword-of (sym)
  247.   "Return a keyword that is naturally associated with symbol SYM.
  248. If SYM is keyword, the value is SYM.
  249. Otherwise it is a keyword whose name is `:' followed by SYM's name."
  250.   (cond ((keywordp sym)
  251.          sym)
  252.         ((symbolp sym)
  253.          (let ((newsym (intern (concat ":" (symbol-name sym)))))
  254.            (set newsym newsym)))
  255.         (t
  256.          (error "expected a symbol, not `%s'" (prin1-to-string sym)))))
  257.  
  258. ;;; Temporary symbols.  
  259. ;;; 
  260.  
  261. (defvar *gentemp-index* 0
  262.   "Integer used by gentemp to produce new names.")
  263.  
  264. (defvar *gentemp-prefix* "T$$_"
  265.   "Names generated by gentemp begin with this string by default.")
  266.  
  267. (defun gentemp (&optional prefix oblist)
  268.   "Generate a fresh interned symbol.
  269. There are 2 optional arguments, PREFIX and OBLIST.  PREFIX is the
  270. string that begins the new name, OBLIST is the obarray used to search for
  271. old names.  The defaults are just right, YOU SHOULD NEVER NEED THESE
  272. ARGUMENTS IN YOUR OWN CODE."
  273.   (if (null prefix)
  274.       (setq prefix *gentemp-prefix*))
  275.   (if (null oblist)
  276.       (setq oblist obarray))            ;default for the intern functions
  277.   (let ((newsymbol nil)
  278.         (newname))
  279.     (while (not newsymbol)
  280.       (setq newname (concat prefix *gentemp-index*))
  281.       (setq *gentemp-index* (+ *gentemp-index* 1))
  282.       (if (not (intern-soft newname oblist))
  283.           (setq newsymbol (intern newname oblist))))
  284.     newsymbol))
  285.  
  286. (defvar *gensym-index* 0
  287.   "Integer used by gensym to produce new names.")
  288.  
  289. (defvar *gensym-prefix* "G$$_"
  290.   "Names generated by gensym begin with this string by default.")
  291.  
  292. (defun gensym (&optional prefix)
  293.   "Generate a fresh uninterned symbol.
  294. There is an  optional argument, PREFIX.  PREFIX is the
  295. string that begins the new name. Most people take just the default,
  296. except when debugging needs suggest otherwise."
  297.   (if (null prefix)
  298.       (setq prefix *gensym-prefix*))
  299.   (let ((newsymbol nil)
  300.         (newname   ""))
  301.     (while (not newsymbol)
  302.       (setq newname (concat prefix *gensym-index*))
  303.       (setq *gensym-index* (+ *gensym-index* 1))
  304.       (if (not (intern-soft newname))
  305.           (setq newsymbol (make-symbol newname))))
  306.     newsymbol))
  307.  
  308. ;;;; end of cl-symbols.el
  309.  
  310. ;;;; CONDITIONALS
  311. ;;;;    This file provides some of the conditional constructs of
  312. ;;;;    Common Lisp.  Total compatibility is again impossible, as the
  313. ;;;;    'if' form is different in both languages, so only a good
  314. ;;;;    approximation is desired.
  315. ;;;;
  316. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  317. ;;;;       (quiroz@cs.rochester.edu)
  318.  
  319. ;;; indentation info
  320. (put 'case      'lisp-indent-hook 1)
  321. (put 'ecase     'lisp-indent-hook 1)
  322. (put 'when      'lisp-indent-hook 1)
  323. (put 'unless    'lisp-indent-hook 1)
  324.  
  325. ;;; WHEN and UNLESS
  326. ;;; These two forms are simplified ifs, with a single branch.
  327.  
  328. (defmacro when (condition &rest body)
  329.   "(when CONDITION . BODY) => evaluate BODY if CONDITION is true."
  330.   (list* 'if (list 'not condition) '() body))
  331.  
  332. (defmacro unless (condition &rest body)
  333.   "(unless CONDITION . BODY) => evaluate BODY if CONDITION is false."
  334.   (list* 'if condition '() body))
  335.  
  336. ;;; CASE and ECASE
  337. ;;; CASE selects among several clauses, based on the value (evaluated)
  338. ;;; of a expression and a list of (unevaluated) key values.  ECASE is
  339. ;;; the same, but signals an error if no clause is activated.
  340.  
  341. (defmacro case (expr &rest cases)
  342.   "(case EXPR . CASES) => evals EXPR, chooses from CASES on that value.
  343. EXPR   -> any form
  344. CASES  -> list of clauses, non empty
  345. CLAUSE -> HEAD . BODY
  346. HEAD   -> t             = catch all, must be last clause
  347.        -> otherwise     = same as t
  348.        -> nil           = illegal
  349.        -> atom          = activated if (eql  EXPR HEAD)
  350.        -> list of atoms = activated if (memq EXPR HEAD)
  351. BODY   -> list of forms, implicit PROGN is built around it.
  352. EXPR is evaluated only once."
  353.   (let* ((newsym (gentemp))
  354.          (clauses (case-clausify cases newsym)))
  355.     ;; convert case into a cond inside a let
  356.     (list 'let
  357.          (list (list newsym expr))
  358.          (list* 'cond (nreverse clauses)))))
  359.  
  360. (defmacro ecase (expr &rest cases)
  361.   "(ecase EXPR . CASES) => like `case', but error if no case fits.
  362. `t'-clauses are not allowed."
  363.   (let* ((newsym (gentemp))
  364.          (clauses (case-clausify cases newsym)))
  365.     ;; check that no 't clause is present.
  366.     ;; case-clausify would put one such at the beginning of clauses
  367.     (if (eq (caar clauses) t)
  368.         (error "no clause-head should be `t' or `otherwise' for `ecase'"))
  369.     ;; insert error-catching clause
  370.     (setq clauses
  371.           (cons
  372.            (list 't (list 'error
  373.                           "ecase on %s = %s failed to take any branch"
  374.                           (list 'quote expr)
  375.                           (list 'prin1-to-string newsym)))
  376.            clauses))
  377.     ;; generate code as usual
  378.     (list 'let
  379.           (list (list newsym expr))
  380.           (list* 'cond (nreverse clauses)))))
  381.  
  382.  
  383. (defun case-clausify (cases newsym)
  384.   "CASE-CLAUSIFY CASES NEWSYM => clauses for a 'cond'
  385. Converts the CASES of a [e]case macro into cond clauses to be
  386. evaluated inside a let that binds NEWSYM.  Returns the clauses in
  387. reverse order."
  388.   (do* ((currentpos cases        (cdr currentpos))
  389.         (nextpos    (cdr cases)  (cdr nextpos))
  390.         (curclause  (car cases)  (car currentpos))
  391.         (result     '()))
  392.       ((endp currentpos) result)
  393.     (let ((head (car curclause))
  394.           (body (cdr curclause)))
  395.       ;; construct a cond-clause according to the head
  396.       (cond ((null head)
  397.              (error "case clauses cannot have null heads: `%s'"
  398.                     (prin1-to-string curclause)))
  399.             ((or (eq head 't)
  400.                  (eq head 'otherwise))
  401.              ;; check it is the last clause
  402.              (if (not (endp nextpos))
  403.                  (error "clause with `t' or `otherwise' head must be last"))
  404.              ;; accept this clause as a 't' for cond
  405.              (setq result (cons (cons 't body) result)))
  406.             ((atom head)
  407.              (setq result
  408.                    (cons (cons (list 'eql newsym (list 'quote head)) body)
  409.                          result)))
  410.             ((listp head)
  411.              (setq result
  412.                    (cons (cons (list 'memq newsym (list 'quote head)) body)
  413.                          result)))
  414.             (t
  415.              ;; catch-all for this parser
  416.              (error "don't know how to parse case clause `%s'"
  417.                     (prin1-to-string head)))))))
  418.  
  419. ;;;; end of cl-conditionals.el
  420.  
  421. ;;;; ITERATIONS
  422. ;;;;    This file provides simple iterative macros (a la Common Lisp)
  423. ;;;;    constructed on the basis of let, let* and while, which are the
  424. ;;;;    primitive binding/iteration constructs of Emacs Lisp
  425. ;;;;
  426. ;;;;    The Common Lisp iterations use to have a block named nil
  427. ;;;;    wrapped around them, and allow declarations at the beginning
  428. ;;;;    of their bodies and you can return a value using (return ...).
  429. ;;;;    Nothing of the sort exists in Emacs Lisp, so I haven't tried
  430. ;;;;    to imitate these behaviors.
  431. ;;;;
  432. ;;;;    Other than the above, the semantics of Common Lisp are
  433. ;;;;    correctly reproduced to the extent this was reasonable.
  434. ;;;;
  435. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  436. ;;;;       (quiroz@cs.rochester.edu)
  437.  
  438. ;;; some lisp-indentation information
  439. (put 'do                'lisp-indent-hook 2)
  440. (put 'do*               'lisp-indent-hook 2)
  441. (put 'dolist            'lisp-indent-hook 1)
  442. (put 'dotimes           'lisp-indent-hook 1)
  443. (put 'do-symbols        'lisp-indent-hook 1)
  444. (put 'do-all-symbols    'lisp-indent-hook 1)
  445.  
  446.  
  447. (defmacro do (stepforms endforms &rest body)
  448.   "(do STEPFORMS ENDFORMS . BODY): Iterate BODY, stepping some local variables.
  449. STEPFORMS must be a list of symbols or lists.  In the second case, the
  450. lists must start with a symbol and contain up to two more forms. In
  451. the STEPFORMS, a symbol is the same as a (symbol).  The other 2 forms
  452. are the initial value (def. NIL) and the form to step (def. itself).
  453. The values used by initialization and stepping are computed in parallel.
  454. The ENDFORMS are a list (CONDITION . ENDBODY).  If the CONDITION
  455. evaluates to true in any iteration, ENDBODY is evaluated and the last
  456. form in it is returned.
  457. The BODY (which may be empty) is evaluated at every iteration, with
  458. the symbols of the STEPFORMS bound to the initial or stepped values."
  459.   ;; check the syntax of the macro
  460.   (and (check-do-stepforms stepforms)
  461.        (check-do-endforms endforms))
  462.   ;; construct emacs-lisp equivalent
  463.   (let ((initlist (extract-do-inits stepforms))
  464.         (steplist (extract-do-steps stepforms))
  465.         (endcond  (car endforms))
  466.         (endbody  (cdr endforms)))
  467.     (cons 'let (cons initlist
  468.                      (cons (cons 'while (cons (list 'not endcond) 
  469.                                               (append body steplist)))
  470.                            (append endbody))))))
  471.  
  472.  
  473. (defmacro do* (stepforms endforms &rest body)
  474.   "`do*' is to `do' as `let*' is to `let'.
  475. STEPFORMS must be a list of symbols or lists.  In the second case, the
  476. lists must start with a symbol and contain up to two more forms. In
  477. the STEPFORMS, a symbol is the same as a (symbol).  The other 2 forms
  478. are the initial value (def. NIL) and the form to step (def. itself).
  479. Initializations and steppings are done in the sequence they are written.
  480. The ENDFORMS are a list (CONDITION . ENDBODY).  If the CONDITION
  481. evaluates to true in any iteration, ENDBODY is evaluated and the last
  482. form in it is returned.
  483. The BODY (which may be empty) is evaluated at every iteration, with
  484. the symbols of the STEPFORMS bound to the initial or stepped values."
  485.   ;; check the syntax of the macro
  486.   (and (check-do-stepforms stepforms)
  487.        (check-do-endforms endforms))
  488.   ;; construct emacs-lisp equivalent
  489.   (let ((initlist (extract-do-inits stepforms))
  490.         (steplist (extract-do*-steps stepforms))
  491.         (endcond  (car endforms))
  492.         (endbody  (cdr endforms)))
  493.     (cons 'let* (cons initlist
  494.                      (cons (cons 'while (cons (list 'not endcond) 
  495.                                               (append body steplist)))
  496.                            (append endbody))))))
  497.  
  498.  
  499. ;;; DO and DO* share the syntax checking functions that follow.
  500.  
  501. (defun check-do-stepforms (forms)
  502.   "True if FORMS is a valid stepforms for the do[*] macro (q.v.)"
  503.   (if (nlistp forms)
  504.       (error "init/step form for do[*] should be a list, not `%s'"
  505.              (prin1-to-string forms))
  506.     (mapcar
  507.      (function
  508.       (lambda (entry)
  509.         (if (not (or (symbolp entry)
  510.                      (and (listp entry)
  511.                           (symbolp (car entry))
  512.                           (< (length entry) 4))))
  513.             (error "init/step must be %s, not `%s'"
  514.                    "symbol or (symbol [init [step]])"
  515.                    (prin1-to-string entry)))))
  516.      forms)))
  517.  
  518. (defun check-do-endforms (forms)
  519.   "True if FORMS is a valid endforms for the do[*] macro (q.v.)"
  520.   (if (nlistp forms)
  521.       (error "termination form for do macro should be a list, not `%s'"
  522.              (prin1-to-string forms))))
  523.  
  524. (defun extract-do-inits (forms)
  525.   "Returns a list of the initializations (for do) in FORMS
  526. --a stepforms, see the do macro--. FORMS is assumed syntactically valid."
  527.   (mapcar
  528.    (function
  529.     (lambda (entry)
  530.       (cond ((symbolp entry)
  531.              (list entry nil))
  532.             ((listp entry)
  533.              (list (car entry) (cadr entry))))))
  534.    forms))
  535.  
  536. ;;; There used to be a reason to deal with DO differently than with
  537. ;;; DO*.  The writing of PSETQ has made it largely unnecessary.
  538.  
  539. (defun extract-do-steps (forms)
  540.   "EXTRACT-DO-STEPS FORMS => an s-expr
  541. FORMS is the stepforms part of a DO macro (q.v.).  This function
  542. constructs an s-expression that does the stepping at the end of an
  543. iteration."
  544.   (list (cons 'psetq (select-stepping-forms forms))))
  545.  
  546. (defun extract-do*-steps (forms)
  547.   "EXTRACT-DO*-STEPS FORMS => an s-expr
  548. FORMS is the stepforms part of a DO* macro (q.v.).  This function
  549. constructs an s-expression that does the stepping at the end of an
  550. iteration."
  551.   (list (cons 'setq (select-stepping-forms forms))))
  552.  
  553. (defun select-stepping-forms (forms)
  554.   "Separate only the forms that cause stepping."
  555.   (let ((result '())            ;ends up being (... var form ...)
  556.     (ptr forms)            ;to traverse the forms
  557.     entry                ;to explore each form in turn
  558.     )
  559.     (while ptr                ;(not (endp entry)) might be safer
  560.       (setq entry (car ptr))
  561.       (cond ((and (listp entry) (= (length entry) 3))
  562.              (setq result (append       ;append in reverse order!
  563.                            (list (caddr entry) (car entry))
  564.                            result))))
  565.       (setq ptr (cdr ptr)))        ;step in the list of forms
  566.     (nreverse result)))
  567.  
  568. ;;; Other iterative constructs
  569.  
  570. (defmacro dolist  (stepform &rest body)
  571.   "(dolist (VAR LIST [RESULTFORM]) . BODY): do BODY for each elt of LIST.
  572. The RESULTFORM defaults to nil.  The VAR is bound to successive
  573. elements of the value of LIST and remains bound (to the nil value) when the
  574. RESULTFORM is evaluated."
  575.   ;; check sanity
  576.   (cond
  577.    ((nlistp stepform)
  578.     (error "stepform for `dolist' should be (VAR LIST [RESULT]), not `%s'"
  579.            (prin1-to-string stepform)))
  580.    ((not (symbolp (car stepform)))
  581.     (error "first component of stepform should be a symbol, not `%s'"
  582.            (prin1-to-string (car stepform))))
  583.    ((> (length stepform) 3)
  584.     (error "too many components in stepform `%s'"
  585.            (prin1-to-string stepform))))
  586.   ;; generate code
  587.   (let* ((var (car stepform))
  588.          (listform (cadr stepform))
  589.          (resultform (caddr stepform))
  590.      (listsym (gentemp)))
  591.     (nconc
  592.      (list 'let (list var (list listsym listform))
  593.        (nconc
  594.         (list 'while listsym
  595.           (list 'setq
  596.             var (list 'car listsym)
  597.             listsym (list 'cdr listsym)))
  598.         body))
  599.      (and resultform
  600.       (cons (list 'setq var nil)
  601.         (list resultform))))))
  602.  
  603. (defmacro dotimes (stepform &rest body)
  604.   "(dotimes (VAR COUNTFORM [RESULTFORM]) .  BODY): Repeat BODY, counting in VAR.
  605. The COUNTFORM should return a positive integer.  The VAR is bound to
  606. successive integers from 0 to COUNTFORM-1 and the BODY is repeated for
  607. each of them.  At the end, the RESULTFORM is evaluated and its value
  608. returned. During this last evaluation, the VAR is still bound, and its
  609. value is the number of times the iteration occurred. An omitted RESULTFORM
  610. defaults to nil."
  611.   ;; check sanity 
  612.   (cond
  613.    ((nlistp stepform)
  614.     (error "stepform for `dotimes' should be (VAR COUNT [RESULT]), not `%s'"
  615.            (prin1-to-string stepform)))
  616.    ((not (symbolp (car stepform)))
  617.     (error "first component of stepform should be a symbol, not `%s'"
  618.            (prin1-to-string (car stepform))))
  619.    ((> (length stepform) 3)
  620.     (error "too many components in stepform `%s'"
  621.            (prin1-to-string stepform))))
  622.   ;; generate code
  623.   (let* ((var (car stepform))
  624.          (countform (cadr stepform))
  625.          (resultform (caddr stepform))
  626.          (testsym (if (consp countform) (gentemp) countform)))
  627.     (nconc
  628.     (list
  629.       'let (cons (list var -1)
  630.         (and (not (eq countform testsym))
  631.              (list (list testsym countform))))
  632.       (nconc
  633.        (list 'while (list '< (list 'setq var (list '1+ var)) testsym))
  634.        body))
  635.      (and resultform (list resultform)))))
  636.  
  637. (defmacro do-symbols (stepform &rest body)
  638.   "(do_symbols (VAR [OBARRAY [RESULTFORM]]) . BODY)
  639. The VAR is bound to each of the symbols in OBARRAY (def. obarray) and
  640. the BODY is repeatedly performed for each of those bindings. At the
  641. end, RESULTFORM (def. nil) is evaluated and its value returned.
  642. During this last evaluation, the VAR is still bound and its value is nil.
  643. See also the function `mapatoms'."
  644.   ;; check sanity
  645.   (cond
  646.    ((nlistp stepform)
  647.     (error "stepform for `do-symbols' should be (VAR OBARRAY [RESULT]), not `%s'"
  648.            (prin1-to-string stepform)))
  649.    ((not (symbolp (car stepform)))
  650.     (error "first component of stepform should be a symbol, not `%s'"
  651.            (prin1-to-string (car stepform))))
  652.    ((> (length stepform) 3)
  653.     (error "too many components in stepform `%s'"
  654.            (prin1-to-string stepform))))
  655.   ;; generate code
  656.   (let* ((var (car stepform))
  657.          (oblist (cadr stepform))
  658.          (resultform (caddr stepform)))
  659.     (list 'progn
  660.           (list 'mapatoms
  661.                 (list 'function
  662.                       (cons 'lambda (cons (list var) body)))
  663.                 oblist)
  664.           (list 'let
  665.                 (list (list var nil))
  666.                 resultform))))
  667.  
  668.  
  669. (defmacro do-all-symbols (stepform &rest body)
  670.   "(do-all-symbols (VAR [RESULTFORM]) . BODY)
  671. Is the same as (do-symbols (VAR obarray RESULTFORM) . BODY)."
  672.   (list*
  673.    'do-symbols
  674.    (list (car stepform) 'obarray (cadr stepform))
  675.    body))
  676.  
  677. (defmacro loop (&rest body)
  678.   "(loop . BODY) repeats BODY indefinitely and does not return.
  679. Normally BODY uses `throw' or `signal' to cause an exit.
  680. The forms in BODY should be lists, as non-lists are reserved for new features."
  681.   ;; check that the body doesn't have atomic forms
  682.   (if (nlistp body)
  683.       (error "body of `loop' should be a list of lists or nil")
  684.     ;; ok, it is a list, check for atomic components
  685.     (mapcar
  686.      (function (lambda (component)
  687.                  (if (nlistp component)
  688.                      (error "components of `loop' should be lists"))))
  689.      body)
  690.     ;; build the infinite loop
  691.     (cons 'while (cons 't body))))
  692.  
  693. ;;;; end of cl-iterations.el
  694.  
  695. ;;;; LISTS
  696. ;;;;    This file provides some of the lists machinery of Common-Lisp
  697. ;;;;    in a way compatible with Emacs Lisp.  Especially, see the the
  698. ;;;;    typical c[ad]*r functions.
  699. ;;;;
  700. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  701. ;;;;       (quiroz@cs.rochester.edu)
  702.  
  703. ;;; Synonyms for list functions
  704. (defsubst first (x)
  705.   "Synonym for `car'"
  706.   (car x))
  707.  
  708. (defsubst second (x)
  709.   "Return the second element of the list LIST."
  710.   (nth 1 x))
  711.  
  712. (defsubst third (x)
  713.   "Return the third element of the list LIST."
  714.   (nth 2 x))
  715.  
  716. (defsubst fourth (x)
  717.   "Return the fourth element of the list LIST."
  718.   (nth 3 x))
  719.  
  720. (defsubst fifth (x)
  721.   "Return the fifth element of the list LIST."
  722.   (nth 4 x))
  723.  
  724. (defsubst sixth (x)
  725.   "Return the sixth element of the list LIST."
  726.   (nth 5 x))
  727.  
  728. (defsubst seventh (x)
  729.   "Return the seventh element of the list LIST."
  730.   (nth 6 x))
  731.  
  732. (defsubst eighth (x)
  733.   "Return the eighth element of the list LIST."
  734.   (nth 7 x))
  735.  
  736. (defsubst ninth (x)
  737.   "Return the ninth element of the list LIST."
  738.   (nth 8 x))
  739.  
  740. (defsubst tenth (x)
  741.   "Return the tenth element of the list LIST."
  742.   (nth 9 x))
  743.  
  744. (defsubst rest (x)
  745.   "Synonym for `cdr'"
  746.   (cdr x))
  747.  
  748. (defsubst endp (x)
  749.   "t if X is nil, nil if X is a cons; error otherwise."
  750.   (if (listp x)
  751.       (null x)
  752.     (error "endp received a non-cons, non-null argument `%s'"
  753.        (prin1-to-string x))))
  754.  
  755. (defun last (x)
  756.   "Returns the last link in the list LIST."
  757.   (if (nlistp x)
  758.       (error "arg to `last' must be a list"))
  759.   (do ((current-cons    x       (cdr current-cons))
  760.        (next-cons    (cdr x)    (cdr next-cons)))
  761.       ((endp next-cons) current-cons)))
  762.  
  763. (defun list-length (x)                  ;taken from CLtL sect. 15.2
  764.   "Returns the length of a non-circular list, or `nil' for a circular one."
  765.   (do ((n 0)                            ;counter
  766.        (fast x (cddr fast))             ;fast pointer, leaps by 2
  767.        (slow x (cdr slow))              ;slow pointer, leaps by 1
  768.        (ready nil))                     ;indicates termination
  769.       (ready n)
  770.     (cond ((endp fast)
  771.            (setq ready t))              ;return n
  772.           ((endp (cdr fast))
  773.            (setq n (+ n 1))
  774.            (setq ready t))              ;return n+1
  775.           ((and (eq fast slow) (> n 0))
  776.            (setq n nil)
  777.            (setq ready t))              ;return nil
  778.           (t
  779.            (setq n (+ n 2))))))         ;just advance counter
  780.  
  781. (defun butlast (list &optional n)
  782.   "Return a new list like LIST but sans the last N elements.
  783. N defaults to 1.  If the list doesn't have N elements, nil is returned."
  784.   (if (null n) (setq n 1))
  785.   (nreverse (nthcdr n (reverse list)))) ;optim. due to macrakis@osf.org
  786.  
  787. ;;; This version due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
  788. (defun list* (arg &rest others)
  789.   "Return a new list containing the first arguments consed onto the last arg.
  790. Thus, (list* 1 2 3 '(a b)) returns (1 2 3 a b)."
  791.   (if (null others)
  792.       arg
  793.       (let* ((others (cons arg (copy-sequence others)))
  794.          (a others))
  795.     (while (cdr (cdr a))
  796.       (setq a (cdr a)))
  797.     (setcdr a (car (cdr a)))
  798.     others)))
  799.  
  800. (defun adjoin (item list)
  801.   "Return a list which contains ITEM but is otherwise like LIST.
  802. If ITEM occurs in LIST, the value is LIST.  Otherwise it is (cons ITEM LIST).
  803. When comparing ITEM against elements, `eql' is used."
  804.   (if (memq item list)
  805.       list
  806.     (cons item list)))
  807.  
  808. (defun ldiff (list sublist)
  809.   "Return a new list like LIST but sans SUBLIST.
  810. SUBLIST must be one of the links in LIST; otherwise the value is LIST itself."
  811.   (do ((result '())
  812.        (curcons list (cdr curcons)))
  813.       ((or (endp curcons) (eq curcons sublist))
  814.        (reverse result))
  815.     (setq result (cons (car curcons) result))))
  816.  
  817. ;;; The popular c[ad]*r functions and other list accessors.
  818.  
  819. ;;; To implement this efficiently, a new byte compile handler is used to
  820. ;;; generate the minimal code, saving one function call.
  821.  
  822. (defsubst caar (X)
  823.   "Return the car of the car of X."
  824.   (car (car X)))
  825.  
  826. (defsubst cadr (X)
  827.   "Return the car of the cdr of X."
  828.   (car (cdr X)))
  829.  
  830. (defsubst cdar (X)
  831.   "Return the cdr of the car of X."
  832.   (cdr (car X)))
  833.  
  834. (defsubst cddr (X)
  835.   "Return the cdr of the cdr of X."
  836.   (cdr (cdr X)))
  837.  
  838. (defsubst caaar (X)
  839.   "Return the car of the car of the car of X."
  840.   (car (car (car X))))
  841.  
  842. (defsubst caadr (X)
  843.   "Return the car of the car of the cdr of X."
  844.   (car (car (cdr X))))
  845.  
  846. (defsubst cadar (X)
  847.   "Return the car of the cdr of the car of X."
  848.   (car (cdr (car X))))
  849.  
  850. (defsubst cdaar (X)
  851.   "Return the cdr of the car of the car of X."
  852.   (cdr (car (car X))))
  853.  
  854. (defsubst caddr (X)
  855.   "Return the car of the cdr of the cdr of X."
  856.   (car (cdr (cdr X))))
  857.  
  858. (defsubst cdadr (X)
  859.   "Return the cdr of the car of the cdr of X."
  860.   (cdr (car (cdr X))))
  861.  
  862. (defsubst cddar (X)
  863.   "Return the cdr of the cdr of the car of X."
  864.   (cdr (cdr (car X))))
  865.  
  866. (defsubst cdddr (X)
  867.   "Return the cdr of the cdr of the cdr of X."
  868.   (cdr (cdr (cdr X))))
  869.  
  870. (defsubst caaaar (X)
  871.   "Return the car of the car of the car of the car of X."
  872.   (car (car (car (car X)))))
  873.  
  874. (defsubst caaadr (X)
  875.   "Return the car of the car of the car of the cdr of X."
  876.   (car (car (car (cdr X)))))
  877.  
  878. (defsubst caadar (X)
  879.   "Return the car of the car of the cdr of the car of X."
  880.   (car (car (cdr (car X)))))
  881.  
  882. (defsubst cadaar (X)
  883.   "Return the car of the cdr of the car of the car of X."
  884.   (car (cdr (car (car X)))))
  885.  
  886. (defsubst cdaaar (X)
  887.   "Return the cdr of the car of the car of the car of X."
  888.   (cdr (car (car (car X)))))
  889.  
  890. (defsubst caaddr (X)
  891.   "Return the car of the car of the cdr of the cdr of X."
  892.   (car (car (cdr (cdr X)))))
  893.  
  894. (defsubst cadadr (X)
  895.   "Return the car of the cdr of the car of the cdr of X."
  896.   (car (cdr (car (cdr X)))))
  897.  
  898. (defsubst cdaadr (X)
  899.   "Return the cdr of the car of the car of the cdr of X."
  900.   (cdr (car (car (cdr X)))))
  901.  
  902. (defsubst caddar (X)
  903.   "Return the car of the cdr of the cdr of the car of X."
  904.   (car (cdr (cdr (car X)))))
  905.  
  906. (defsubst cdadar (X)
  907.   "Return the cdr of the car of the cdr of the car of X."
  908.   (cdr (car (cdr (car X)))))
  909.  
  910. (defsubst cddaar (X)
  911.   "Return the cdr of the cdr of the car of the car of X."
  912.   (cdr (cdr (car (car X)))))
  913.  
  914. (defsubst cadddr (X)
  915.   "Return the car of the cdr of the cdr of the cdr of X."
  916.   (car (cdr (cdr (cdr X)))))
  917.  
  918. (defsubst cddadr (X)
  919.   "Return the cdr of the cdr of the car of the cdr of X."
  920.   (cdr (cdr (car (cdr X)))))
  921.  
  922. (defsubst cdaddr (X)
  923.   "Return the cdr of the car of the cdr of the cdr of X."
  924.   (cdr (car (cdr (cdr X)))))
  925.  
  926. (defsubst cdddar (X)
  927.   "Return the cdr of the cdr of the cdr of the car of X."
  928.   (cdr (cdr (cdr (car X)))))
  929.  
  930. (defsubst cddddr (X)
  931.   "Return the cdr of the cdr of the cdr of the cdr of X."
  932.   (cdr (cdr (cdr (cdr X)))))
  933.  
  934. ;;; some inverses of the accessors are needed for setf purposes
  935.  
  936. (defsubst setnth (n list newval)
  937.   "Set (nth N LIST) to NEWVAL.  Returns NEWVAL."
  938.   (rplaca (nthcdr n list) newval))
  939.  
  940. (defun setnthcdr (n list newval)
  941.   "(setnthcdr N LIST NEWVAL) => NEWVAL
  942. As a side effect, sets the Nth cdr of LIST to NEWVAL."
  943.   (when (< n 0)
  944.     (error "N must be 0 or greater, not %d" n))
  945.   (while (> n 0)
  946.     (setq list (cdr list)
  947.           n    (- n 1)))
  948.   ;; here only if (zerop n)
  949.   (rplaca list (car newval))
  950.   (rplacd list (cdr newval))
  951.   newval)
  952.  
  953. ;;; A-lists machinery
  954.  
  955. (defsubst acons (key item alist)
  956.   "Return a new alist with KEY paired with ITEM; otherwise like ALIST.
  957. Does not copy ALIST."
  958.   (cons (cons key item) alist))
  959.  
  960. (defun pairlis (keys data &optional alist)
  961.   "Return a new alist with each elt of KEYS paired with an elt of DATA;
  962. optional 3rd arg ALIST is nconc'd at the end.  KEYS and DATA must
  963. have the same length."
  964.   (unless (= (length keys) (length data))
  965.     (error "keys and data should be the same length"))
  966.   (do* ;;collect keys and data in front of alist
  967.       ((kptr keys (cdr kptr))           ;traverses the keys
  968.        (dptr data (cdr dptr))           ;traverses the data
  969.        (key (car kptr) (car kptr))      ;current key
  970.        (item (car dptr) (car dptr))     ;current data item
  971.        (result alist))
  972.       ((endp kptr) result)
  973.     (setq result (acons key item result))))
  974.  
  975. ;;;; end of cl-lists.el
  976.  
  977. ;;;; SEQUENCES
  978. ;;;; Emacs Lisp provides many of the 'sequences' functionality of
  979. ;;;; Common Lisp.  This file provides a few things that were left out.
  980. ;;;; 
  981.  
  982.  
  983. (defkeyword :test           "Used to designate positive (selection) tests.")
  984. (defkeyword :test-not       "Used to designate negative (rejection) tests.")
  985. (defkeyword :key            "Used to designate component extractions.")
  986. (defkeyword :predicate      "Used to define matching of sequence components.")
  987. (defkeyword :start          "Inclusive low index in sequence")
  988. (defkeyword :end            "Exclusive high index in sequence")
  989. (defkeyword :start1         "Inclusive low index in first of two sequences.")
  990. (defkeyword :start2         "Inclusive low index in second of two sequences.")
  991. (defkeyword :end1           "Exclusive high index in first of two sequences.")
  992. (defkeyword :end2           "Exclusive high index in second of two sequences.")
  993. (defkeyword :count          "Number of elements to affect.")
  994. (defkeyword :from-end       "T when counting backwards.")
  995. (defkeyword :initial-value  "For the syntax of #'reduce")
  996.  
  997. (defun some     (pred seq &rest moreseqs)
  998.   "Test PREDICATE on each element of SEQUENCE; is it ever non-nil?
  999. Extra args are additional sequences; PREDICATE gets one arg from each
  1000. sequence and we advance down all the sequences together in lock-step.
  1001. A sequence means either a list or a vector."
  1002.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1003.     (do* ((ready nil)                   ;flag: return when t
  1004.           (result nil)                  ;resulting value
  1005.           (applyval nil)                ;result of applying pred once
  1006.           (remaining args
  1007.                      (cdr remaining))   ;remaining argument sets
  1008.           (current (car remaining)      ;current argument set
  1009.                    (car remaining)))
  1010.         ((or ready (endp remaining)) result)
  1011.       (setq applyval (apply pred current))
  1012.       (when applyval
  1013.         (setq ready t)
  1014.         (setq result applyval)))))
  1015.  
  1016. (defun every    (pred seq &rest moreseqs)
  1017.   "Test PREDICATE on each element of SEQUENCE; is it always non-nil?
  1018. Extra args are additional sequences; PREDICATE gets one arg from each
  1019. sequence and we advance down all the sequences together in lock-step.
  1020. A sequence means either a list or a vector."
  1021.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1022.     (do* ((ready nil)                   ;flag: return when t
  1023.           (result t)                    ;resulting value
  1024.           (applyval nil)                ;result of applying pred once
  1025.           (remaining args
  1026.                      (cdr remaining))   ;remaining argument sets
  1027.           (current (car remaining)      ;current argument set
  1028.                    (car remaining)))
  1029.         ((or ready (endp remaining)) result)
  1030.       (setq applyval (apply pred current))
  1031.       (unless applyval
  1032.         (setq ready t)
  1033.         (setq result nil)))))
  1034.  
  1035. (defun notany   (pred seq &rest moreseqs)
  1036.   "Test PREDICATE on each element of SEQUENCE; is it always nil?
  1037. Extra args are additional sequences; PREDICATE gets one arg from each
  1038. sequence and we advance down all the sequences together in lock-step.
  1039. A sequence means either a list or a vector."
  1040.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1041.     (do* ((ready nil)                   ;flag: return when t
  1042.           (result t)                    ;resulting value
  1043.           (applyval nil)                ;result of applying pred once
  1044.           (remaining args
  1045.                      (cdr remaining))   ;remaining argument sets
  1046.           (current (car remaining)      ;current argument set
  1047.                    (car remaining)))
  1048.         ((or ready (endp remaining)) result)
  1049.       (setq applyval (apply pred current))
  1050.       (when applyval
  1051.         (setq ready t)
  1052.         (setq result nil)))))
  1053.  
  1054. (defun notevery (pred seq &rest moreseqs)
  1055.   "Test PREDICATE on each element of SEQUENCE; is it sometimes nil?
  1056. Extra args are additional sequences; PREDICATE gets one arg from each
  1057. sequence and we advance down all the sequences together in lock-step.
  1058. A sequence means either a list or a vector."
  1059.   (let ((args  (reassemble-argslists (list* seq moreseqs))))
  1060.     (do* ((ready nil)                   ;flag: return when t
  1061.           (result nil)                  ;resulting value
  1062.           (applyval nil)                ;result of applying pred once
  1063.           (remaining args
  1064.                      (cdr remaining))   ;remaining argument sets
  1065.           (current (car remaining)      ;current argument set
  1066.                    (car remaining)))
  1067.         ((or ready (endp remaining)) result)
  1068.       (setq applyval (apply pred current))
  1069.       (unless applyval
  1070.         (setq ready t)
  1071.         (setq result t)))))
  1072.  
  1073. ;;; More sequence functions that don't need keyword arguments
  1074.  
  1075. (defun concatenate (type &rest sequences)
  1076.   "(concatenate TYPE &rest SEQUENCES) => a sequence
  1077. The sequence returned is of type TYPE (must be 'list, 'string, or 'vector) and
  1078. contains the concatenation of the elements of all the arguments, in the order
  1079. given."
  1080.   (let ((sequences (append sequences '(()))))
  1081.     (case type
  1082.       (list
  1083.        (apply (function append) sequences))
  1084.       (string
  1085.        (apply (function concat) sequences))
  1086.       (vector
  1087.        (apply (function vector) (apply (function append) sequences)))
  1088.       (t
  1089.        (error "type for concatenate `%s' not 'list, 'string or 'vector"
  1090.               (prin1-to-string type))))))
  1091.  
  1092. (defun map (type function &rest sequences)
  1093.   "(map TYPE FUNCTION &rest SEQUENCES) => a sequence
  1094. The FUNCTION is called on each set of elements from the SEQUENCES \(stopping
  1095. when the shortest sequence is terminated\) and the results are possibly
  1096. returned in a sequence of type TYPE \(one of 'list, 'vector, 'string, or nil\)
  1097. giving NIL for TYPE gets rid of the values."
  1098.   (if (not (memq type (list 'list 'string 'vector nil)))
  1099.       (error "type for map `%s' not 'list, 'string, 'vector or nil"
  1100.              (prin1-to-string type)))
  1101.   (let ((argslists (reassemble-argslists sequences))
  1102.         results)
  1103.     (if (null type)
  1104.         (while argslists                ;don't bother accumulating
  1105.           (apply function (car argslists))
  1106.           (setq argslists (cdr argslists)))
  1107.       (setq results (mapcar (function (lambda (args) (apply function args)))
  1108.                             argslists))
  1109.       (case type
  1110.         (list
  1111.          results)
  1112.         (string
  1113.          (funcall (function concat) results))
  1114.         (vector
  1115.          (apply (function vector) results))))))
  1116.  
  1117. ;;; an inverse of elt is needed for setf purposes
  1118.  
  1119. (defun setelt (seq n newval)
  1120.   "In SEQUENCE, set the Nth element to NEWVAL.  Returns NEWVAL.
  1121. A sequence means either a list or a vector."
  1122.   (let ((l (length seq)))
  1123.     (if (or (< n 0) (>= n l))
  1124.         (error "N(%d) should be between 0 and %d" n l)
  1125.       ;; only two cases need be considered valid, as strings are arrays
  1126.       (cond ((listp seq)
  1127.              (setnth n seq newval))
  1128.             ((arrayp seq)
  1129.              (aset seq n newval))
  1130.             (t
  1131.              (error "SEQ should be a sequence, not `%s'"
  1132.                     (prin1-to-string seq)))))))
  1133.  
  1134. ;;; Testing with keyword arguments.
  1135. ;;;
  1136. ;;; Many of the sequence functions use keywords to denote some stylized
  1137. ;;; form of selecting entries in a sequence.  The involved arguments
  1138. ;;; are collected with a &rest marker (as Emacs Lisp doesn't have a &key
  1139. ;;; marker), then they are passed to build-klist, who
  1140. ;;; constructs an association list.  That association list is used to
  1141. ;;; test for satisfaction and matching.
  1142.  
  1143. ;;; DON'T USE MEMBER, NOR ANY FUNCTION THAT COULD TAKE KEYWORDS HERE!!!
  1144.  
  1145. (defun build-klist (argslist acceptable &optional allow-other-keys)
  1146.   "Decode a keyword argument list ARGSLIST for keywords in ACCEPTABLE.
  1147. ARGSLIST is a list, presumably the &rest argument of a call, whose
  1148. even numbered elements must be keywords.
  1149. ACCEPTABLE is a list of keywords, the only ones that are truly acceptable.
  1150. The result is an alist containing the arguments named by the keywords
  1151. in ACCEPTABLE, or an error is signalled, if something failed.
  1152. If the third argument (an optional) is non-nil, other keys are acceptable."
  1153.   ;; check legality of the arguments, then destructure them
  1154.   (unless (and (listp argslist)
  1155.                (evenp (length argslist)))
  1156.     (error "build-klist: odd number of keyword-args"))
  1157.   (unless (and (listp acceptable)
  1158.                (every 'keywordp acceptable))
  1159.     (error "build-klist: second arg should be a list of keywords"))
  1160.   (multiple-value-bind
  1161.       (keywords forms)
  1162.       (unzip-list argslist)
  1163.     (unless (every 'keywordp keywords)
  1164.       (error "build-klist: expected keywords, found `%s'"
  1165.              (prin1-to-string keywords)))
  1166.     (unless (or allow-other-keys
  1167.                 (every (function (lambda (keyword)
  1168.                                    (memq keyword acceptable)))
  1169.                        keywords))
  1170.       (error "bad keyword[s]: %s not in %s"
  1171.              (prin1-to-string (mapcan (function (lambda (keyword)
  1172.                                                   (if (memq keyword acceptable)
  1173.                                                       nil
  1174.                                                     (list keyword))))
  1175.                                       keywords))
  1176.              (prin1-to-string acceptable)))
  1177.     (do* ;;pick up the pieces
  1178.         ((auxlist                       ;auxiliary a-list, may
  1179.           (pairlis keywords forms))     ;contain repetitions and junk
  1180.          (ptr    acceptable  (cdr ptr)) ;pointer in acceptable
  1181.          (this  (car ptr)  (car ptr))   ;current acceptable keyword
  1182.          (auxval nil)                   ;used to move values around
  1183.          (alist  '()))                  ;used to build the result
  1184.         ((endp ptr) alist)
  1185.       ;; if THIS appears in auxlist, use its value
  1186.       (when (setq auxval (assq this auxlist))
  1187.         (setq alist (cons auxval alist))))))
  1188.  
  1189.  
  1190. (defun extract-from-klist (klist key &optional default)
  1191.   "(extract-from-klist KLIST KEY [DEFAULT]) => value of KEY or DEFAULT
  1192. Extract value associated with KEY in KLIST (return DEFAULT if nil)."
  1193.   (let ((retrieved (cdr (assq key klist))))
  1194.     (or retrieved default)))
  1195.  
  1196. (defun keyword-argument-supplied-p (klist key)
  1197.   "(keyword-argument-supplied-p KLIST KEY) => nil or something
  1198. NIL if KEY (a keyword) does not appear in the KLIST."
  1199.   (assq key klist))
  1200.  
  1201. (defun add-to-klist (key item klist)
  1202.   "(ADD-TO-KLIST KEY ITEM KLIST) => new KLIST
  1203. Add association (KEY . ITEM) to KLIST."
  1204.   (setq klist (acons key item klist)))
  1205.  
  1206. (defun elt-satisfies-test-p (item elt klist)
  1207.   "(elt-satisfies-test-p ITEM ELT KLIST) => t or nil
  1208. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1209. True if the given ITEM and ELT satisfy the test."
  1210.   (let ((test     (extract-from-klist klist :test))
  1211.         (test-not (extract-from-klist klist :test-not))
  1212.         (keyfn    (extract-from-klist klist :key 'identity)))
  1213.     (cond (test
  1214.            (funcall test item (funcall keyfn elt)))
  1215.           (test-not
  1216.            (not (funcall test-not item (funcall keyfn elt))))
  1217.           (t                            ;should never happen
  1218.            (error "neither :test nor :test-not in `%s'"
  1219.                   (prin1-to-string klist))))))
  1220.  
  1221. (defun elt-satisfies-if-p   (item klist)
  1222.   "(elt-satisfies-if-p ITEM KLIST) => t or nil
  1223. True if an -if style function was called and ITEM satisfies the
  1224. predicate under :predicate in KLIST."
  1225.   (let ((predicate (extract-from-klist klist :predicate))
  1226.         (keyfn     (extract-from-klist klist :key 'identity)))
  1227.     (funcall predicate (funcall keyfn item))))
  1228.  
  1229. (defun elt-satisfies-if-not-p (item klist)
  1230.   "(elt-satisfies-if-not-p ITEM KLIST) => t or nil
  1231. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1232. True if an -if-not style function was called and ITEM does not satisfy
  1233. the predicate under :predicate in KLIST."
  1234.   (let ((predicate (extract-from-klist klist :predicate))
  1235.         (keyfn     (extract-from-klist klist :key 'identity)))
  1236.     (not (funcall predicate (funcall keyfn item)))))
  1237.  
  1238. (defun elts-match-under-klist-p (e1 e2 klist)
  1239.   "(elts-match-under-klist-p E1 E2 KLIST) => t or nil
  1240. KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
  1241. True if elements E1 and E2 match under the tests encoded in KLIST."
  1242.   (let ((test     (extract-from-klist klist :test))
  1243.         (test-not (extract-from-klist klist :test-not))
  1244.         (keyfn    (extract-from-klist klist :key 'identity)))
  1245.     (if (and test test-not)
  1246.         (error "both :test and :test-not in `%s'"
  1247.                (prin1-to-string klist)))
  1248.     (cond (test
  1249.            (funcall test (funcall keyfn e1) (funcall keyfn e2)))
  1250.           (test-not
  1251.            (not (funcall test-not (funcall keyfn e1) (funcall keyfn e2))))
  1252.           (t                            ;should never happen
  1253.            (error "neither :test nor :test-not in `%s'"
  1254.                   (prin1-to-string klist))))))
  1255.  
  1256. ;;; This macro simplifies using keyword args.  It is less clumsy than using
  1257. ;;; the primitives build-klist, etc...  For instance, member could be written
  1258. ;;; this way:
  1259.  
  1260. ;;; (defun member (item list &rest kargs)
  1261. ;;;  (with-keyword-args kargs (test test-not (key 'identity))
  1262. ;;;    ...))
  1263.  
  1264. ;;; Suggested by Robert Potter (potter@cs.rochester.edu, 15 Nov 1989)
  1265.  
  1266. (defmacro with-keyword-args (keyargslist vardefs &rest body)
  1267.   "(WITH-KEYWORD-ARGS KEYARGSLIST VARDEFS . BODY)
  1268. KEYARGSLIST can be either a symbol or a list of one or two symbols.  
  1269. In the second case, the second symbol is either T or NIL, indicating whether
  1270. keywords other than the mentioned ones are tolerable.
  1271.  
  1272. VARDEFS is a list.  Each entry is either a VAR (symbol) or matches
  1273. \(VAR [DEFAULT [KEYWORD]]).  Just giving VAR is the same as giving
  1274. \(VAR nil :VAR).
  1275.  
  1276. The BODY is executed in an environment where each VAR (a symbol) is bound to
  1277. the value present in the KEYARGSLIST provided, or to the DEFAULT.  The value
  1278. is searched by using the keyword form of VAR (i.e., :VAR) or the optional
  1279. keyword if provided.
  1280.  
  1281. Notice that this macro doesn't distinguish between a default value given
  1282. explicitly by the user and one provided by default.  See also the more
  1283. primitive functions build-klist, add-to-klist, extract-from-klist,
  1284. keyword-argument-supplied-p, elt-satisfies-test-p, elt-satisfies-if-p,
  1285. elt-satisfies-if-not-p, elts-match-under-klist-p.  They provide more complete,
  1286. if clumsier, control over this feature."
  1287.   (let (allow-other-keys)
  1288.     (if (listp keyargslist)
  1289.         (if (> (length keyargslist) 2)
  1290.             (error
  1291.              "`%s' should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
  1292.              (prin1-to-string keyargslist))
  1293.           (setq allow-other-keys (cadr keyargslist)
  1294.                 keyargslist      (car keyargslist))
  1295.           (if (not (and
  1296.                     (symbolp keyargslist)
  1297.                     (memq allow-other-keys '(t nil))))
  1298.               (error
  1299.                "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
  1300.                )))
  1301.       (if (symbolp keyargslist)
  1302.           (setq allow-other-keys nil)
  1303.         (error
  1304.          "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)")))
  1305.     (let (vars defaults keywords forms
  1306.           (klistname (gensym "KLIST_")))
  1307.       (mapcar (function (lambda (entry)
  1308.                           (if (symbolp entry) ;defaulty case
  1309.                               (setq entry (list entry nil (keyword-of entry))))
  1310.                           (let* ((l (length entry))
  1311.                                  (v (car entry))
  1312.                                  (d (cadr entry))
  1313.                                  (k (caddr entry)))
  1314.                             (if (or (< l 1) (> l 3))
  1315.                                 (error
  1316.                                  "`%s' must match (VAR [DEFAULT [KEYWORD]])"
  1317.                                  (prin1-to-string entry)))
  1318.                             (if (or (null v) (not (symbolp v)))
  1319.                                 (error
  1320.                                  "bad variable `%s': must be non-null symbol"
  1321.                                  (prin1-to-string v)))
  1322.                             (setq vars (cons v vars))
  1323.                             (setq defaults (cons d defaults))
  1324.                             (if (< l 3)
  1325.                                 (setq k (keyword-of v)))
  1326.                             (if (and (= l 3)
  1327.                                      (or (null k)
  1328.                                          (not (keywordp k))))
  1329.                                 (error
  1330.                                  "bad keyword `%s'" (prin1-to-string k)))
  1331.                             (setq keywords (cons k keywords))
  1332.                             (setq forms (cons (list v (list 'extract-from-klist
  1333.                                                             klistname
  1334.                                                             k
  1335.                                                             d))
  1336.                                               forms)))))
  1337.               vardefs)
  1338.       (append
  1339.        (list 'let* (nconc (list (list klistname
  1340.                                       (list 'build-klist keyargslist
  1341.                                             (list 'quote keywords)
  1342.                                             allow-other-keys)))
  1343.                           (nreverse forms)))
  1344.        body))))
  1345. (put 'with-keyword-args 'lisp-indent-hook 1)
  1346.  
  1347.  
  1348. ;;; REDUCE
  1349. ;;; It is here mostly as an example of how to use KLISTs.
  1350. ;;;
  1351. ;;; First of all, you need to declare the keywords (done elsewhere in this
  1352. ;;; file):
  1353. ;;;         (defkeyword :from-end "syntax of sequence functions")
  1354. ;;;         (defkeyword :start "syntax of sequence functions")
  1355. ;;; etc...
  1356. ;;;
  1357. ;;; Then, you capture all the possible keyword arguments with a &rest
  1358. ;;; argument.  You can pass that list downward again, of course, but
  1359. ;;; internally you need to parse it into a KLIST (an alist, really).  One uses
  1360. ;;; (build-klist REST-ARGS ACCEPTABLE-KEYWORDS [ALLOW-OTHER]).  You can then
  1361. ;;; test for presence by using (keyword-argument-supplied-p KLIST KEY) and
  1362. ;;; extract a value with (extract-from-klist KLIST KEY [DEFAULT]).
  1363.  
  1364. (defun reduce (function sequence &rest kargs)
  1365.   "Apply FUNCTION (a function of two arguments) to succesive pairs of elements
  1366. from SEQUENCE.  Some keyword arguments are valid after FUNCTION and SEQUENCE:
  1367. :from-end       If non-nil, process the values backwards
  1368. :initial-value  If given, prefix it to the SEQUENCE.  Suffix, if :from-end
  1369. :start          Restrict reduction to the subsequence from this index
  1370. :end            Restrict reduction to the subsequence BEFORE this index.
  1371. If the sequence is empty and no :initial-value is given, the FUNCTION is
  1372. called on zero (not two) arguments.  Otherwise, if there is exactly one
  1373. element in the combination of SEQUENCE and the initial value, that element is
  1374. returned."
  1375.   (let* ((klist (build-klist kargs '(:from-end :start :end :initial-value)))
  1376.          (length (length sequence))
  1377.          (from-end (extract-from-klist klist :from-end))
  1378.          (initial-value-given (keyword-argument-supplied-p
  1379.                                klist :initial-value))
  1380.          (start (extract-from-klist kargs :start 0))
  1381.          (end   (extract-from-klist kargs :end length)))
  1382.     (setq sequence (cl$subseq-as-list sequence start end))
  1383.     (if from-end
  1384.         (setq sequence (reverse sequence)))
  1385.     (if initial-value-given
  1386.         (setq sequence (cons (extract-from-klist klist :initial-value)
  1387.                              sequence)))
  1388.     (if (null sequence)
  1389.         (funcall function)              ;only use of 0 arguments
  1390.       (let* ((result (car sequence))
  1391.              (sequence (cdr sequence)))
  1392.         (while sequence
  1393.           (setq result   (if from-end
  1394.                              (funcall function (car sequence) result)
  1395.                            (funcall function result (car sequence)))
  1396.                 sequence (cdr sequence)))
  1397.         result))))
  1398.  
  1399. (defun cl$subseq-as-list (sequence start end)
  1400.   "(cl$subseq-as-list SEQUENCE START END) => a list"
  1401.   (let ((list (append sequence nil))
  1402.         (length (length sequence))
  1403.         result)
  1404.     (if (< start 0)
  1405.         (error "start should be >= 0, not %d" start))
  1406.     (if (> end length)
  1407.         (error "end should be <= %d, not %d" length end))
  1408.     (if (and (zerop start) (= end length))
  1409.         list
  1410.       (let ((i start)
  1411.             (vector (apply 'vector list)))
  1412.         (while (/= i end)
  1413.           (setq result (cons (elt vector i) result))
  1414.           (setq i      (+ i 1)))
  1415.         (nreverse result)))))
  1416.  
  1417. ;;;; end of cl-sequences.el
  1418.  
  1419. ;;;; Some functions with keyword arguments
  1420. ;;;;
  1421. ;;;; Both list and sequence functions are considered here together.  This
  1422. ;;;; doesn't fit any more with the original split of functions in files.
  1423.  
  1424. (defun member (item list &rest kargs)
  1425.   "Look for ITEM in LIST; return first tail of LIST the car of whose first
  1426. cons cell tests the same as ITEM.  Admits arguments :key, :test, and
  1427. :test-not."
  1428.   (if (null kargs)                      ;treat this fast for efficiency
  1429.       (memq item list)
  1430.     (let* ((klist     (build-klist kargs '(:test :test-not :key)))
  1431.            (test      (extract-from-klist klist :test))
  1432.            (testnot   (extract-from-klist klist :test-not))
  1433.            (key       (extract-from-klist klist :key 'identity)))
  1434.       ;; another workaround allegedly for speed, BLAH
  1435.       (if (and (or (eq test 'eq) (eq test 'eql)
  1436.                    (eq test (symbol-function 'eq))
  1437.                    (eq test (symbol-function 'eql)))
  1438.                (null testnot)
  1439.                (or (eq key 'identity)   ;either by default or so given
  1440.                    (eq key (function identity)) ;could this happen?
  1441.                    (eq key (symbol-function 'identity)) ;sheer paranoia
  1442.                    ))
  1443.           (memq item list)
  1444.         (if (and test testnot)
  1445.             (error ":test and :test-not both specified for member"))
  1446.         (if (not (or test testnot))
  1447.             (setq test 'eql))
  1448.         ;; final hack: remove the indirection through the function names
  1449.         (if testnot
  1450.             (if (symbolp testnot)
  1451.                 (setq testnot (symbol-function testnot)))
  1452.           (if (symbolp test)
  1453.               (setq test (symbol-function test))))
  1454.         (if (symbolp key)
  1455.             (setq key (symbol-function key)))
  1456.         ;; ok, go for it
  1457.         (let ((ptr list)
  1458.               (done nil)
  1459.               (result '()))
  1460.           (if testnot
  1461.               (while (not (or done (endp ptr)))
  1462.                 (cond ((not (funcall testnot item (funcall key (car ptr))))
  1463.                        (setq done t)
  1464.                        (setq result ptr)))
  1465.                 (setq ptr (cdr ptr)))
  1466.             (while (not (or done (endp ptr)))
  1467.                 (cond ((funcall test item (funcall key (car ptr)))
  1468.                        (setq done t)
  1469.                        (setq result ptr)))
  1470.                 (setq ptr (cdr ptr))))
  1471.           result)))))
  1472.  
  1473. ;;;; MULTIPLE VALUES
  1474. ;;;;    This package approximates the behavior of the multiple-values
  1475. ;;;;    forms of Common Lisp.  
  1476. ;;;;
  1477. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1478. ;;;;       (quiroz@cs.rochester.edu)
  1479.  
  1480. ;;; Lisp indentation information
  1481. (put 'multiple-value-bind  'lisp-indent-hook 2)
  1482. (put 'multiple-value-setq  'lisp-indent-hook 2)
  1483. (put 'multiple-value-list  'lisp-indent-hook nil)
  1484. (put 'multiple-value-call  'lisp-indent-hook 1)
  1485. (put 'multiple-value-prog1 'lisp-indent-hook 1)
  1486.  
  1487. ;;; Global state of the package is kept here
  1488. (defvar *mvalues-values* nil
  1489.   "Most recently returned multiple-values")
  1490. (defvar *mvalues-count*  nil
  1491.   "Count of multiple-values returned, or nil if the mechanism was not used")
  1492.  
  1493. ;;; values is the standard multiple-value-return form.  Must be the
  1494. ;;; last thing evaluated inside a function.  If the caller is not
  1495. ;;; expecting multiple values, only the first one is passed.  (values)
  1496. ;;; is the same as no-values returned (unaware callers see nil). The
  1497. ;;; alternative (values-list <list>) is just a convenient shorthand
  1498. ;;; and complements multiple-value-list.
  1499.  
  1500. (defun values (&rest val-forms)
  1501.   "Produce multiple values (zero or more).  Each arg is one value.
  1502. See also `multiple-value-bind', which is one way to examine the
  1503. multiple values produced by a form.  If the containing form or caller
  1504. does not check specially to see multiple values, it will see only
  1505. the first value."
  1506.   (setq *mvalues-values* val-forms)
  1507.   (setq *mvalues-count*  (length *mvalues-values*))
  1508.   (car *mvalues-values*))
  1509.  
  1510. (defun values-list (&optional val-forms)
  1511.   "Produce multiple values (zero or more).  Each element of LIST is one value.
  1512. This is equivalent to (apply 'values LIST)."
  1513.   (cond ((nlistp val-forms)
  1514.          (error "Argument to values-list must be a list, not `%s'"
  1515.                 (prin1-to-string val-forms))))
  1516.   (setq *mvalues-values* val-forms)
  1517.   (setq *mvalues-count* (length *mvalues-values*))
  1518.   (car *mvalues-values*))
  1519.  
  1520. ;;; Callers that want to see the multiple values use these macros.
  1521.  
  1522. (defmacro multiple-value-list (form)
  1523.   "Execute FORM and return a list of all the (multiple) values FORM produces.
  1524. See `values' and `multiple-value-bind'."
  1525.   (list 'progn
  1526.         (list 'setq '*mvalues-count* nil)
  1527.         (list 'let (list (list 'it '(gensym)))
  1528.               (list 'set 'it form)
  1529.               (list 'if '*mvalues-count*
  1530.                     (list 'copy-sequence '*mvalues-values*)
  1531.                     (list 'progn
  1532.                           (list 'setq '*mvalues-count* 1)
  1533.                           (list 'setq '*mvalues-values*
  1534.                                 (list 'list (list 'symbol-value 'it)))
  1535.                           (list 'copy-sequence '*mvalues-values*))))))
  1536.  
  1537. (defmacro multiple-value-call (function &rest args)
  1538.   "Call FUNCTION on all the values produced by the remaining arguments.
  1539. (multiple-value-call '+ (values 1 2) (values 3 4)) is 10."
  1540.   (let* ((result (gentemp))
  1541.          (arg    (gentemp)))
  1542.     (list 'apply (list 'function (eval function))
  1543.           (list 'let* (list (list result '()))
  1544.                 (list 'dolist (list arg (list 'quote args) result)
  1545.                       (list 'setq result
  1546.                             (list 'append
  1547.                                   result
  1548.                                   (list 'multiple-value-list
  1549.                                         (list 'eval arg)))))))))
  1550.  
  1551. (defmacro multiple-value-bind (vars form &rest body)
  1552.   "Bind VARS to the (multiple) values produced by FORM, then do BODY.
  1553. VARS is a list of variables; each is bound to one of FORM's values.
  1554. If FORM doesn't make enough values, the extra variables are bound to nil.
  1555. (Ordinary forms produce only one value; to produce more, use `values'.)
  1556. Extra values are ignored.
  1557. BODY (zero or more forms) is executed with the variables bound,
  1558. then the bindings are unwound."
  1559.   (let* ((vals   (gentemp))             ;name for intermediate values
  1560.          (clauses (mv-bind-clausify     ;convert into clauses usable
  1561.                    vars vals)))         ; in a let form
  1562.     (list* 'let*
  1563.            (cons (list vals (list 'multiple-value-list form))
  1564.                  clauses)
  1565.            body)))
  1566.  
  1567. (defmacro multiple-value-setq (vars form)
  1568.   "Set VARS to the (multiple) values produced by FORM.
  1569. VARS is a list of variables; each is set to one of FORM's values.
  1570. If FORM doesn't make enough values, the extra variables are set to nil.
  1571. (Ordinary forms produce only one value; to produce more, use `values'.)
  1572. Extra values are ignored."
  1573.   (let* ((vals (gentemp))               ;name for intermediate values
  1574.          (clauses (mv-bind-clausify     ;convert into clauses usable
  1575.                    vars vals)))         ; in a setq (after append).
  1576.     (list 'let*
  1577.           (list (list vals (list 'multiple-value-list form)))
  1578.           (cons 'setq (apply (function append) clauses)))))
  1579.  
  1580. (defmacro multiple-value-prog1 (form &rest body)
  1581.   "Evaluate FORM, then BODY, then produce the same values FORM produced.
  1582. Thus, (multiple-value-prog1 (values 1 2) (foobar)) produces values 1 and 2.
  1583. This is like `prog1' except that `prog1' would produce only one value,
  1584. which would be the first of FORM's values."
  1585.   (let* ((heldvalues (gentemp)))
  1586.     (cons 'let*
  1587.           (cons (list (list heldvalues (list 'multiple-value-list form)))
  1588.                 (append body (list (list 'values-list heldvalues)))))))
  1589.  
  1590. ;;; utility functions
  1591. ;;;
  1592. ;;; mv-bind-clausify makes the pairs needed to have the variables in
  1593. ;;; the variable list correspond with the values returned by the form.
  1594. ;;; vals is a fresh symbol that intervenes in all the bindings.
  1595.  
  1596. (defun mv-bind-clausify (vars vals)
  1597.   "MV-BIND-CLAUSIFY VARS VALS => Auxiliary list
  1598. Forms a list of pairs `(,(nth i vars) (nth i vals)) for i from 0 to
  1599. the length of VARS (a list of symbols).  VALS is just a fresh symbol."
  1600.   (if (or (nlistp vars)
  1601.           (notevery 'symbolp vars))
  1602.       (error "expected a list of symbols, not `%s'"
  1603.              (prin1-to-string vars)))
  1604.   (let* ((nvars    (length vars))
  1605.          (clauses '()))
  1606.     (dotimes (n nvars clauses)
  1607.       (setq clauses (cons (list (nth n vars)
  1608.                                 (list 'nth n vals)) clauses)))))
  1609.  
  1610. ;;;; end of cl-multiple-values.el
  1611.  
  1612. ;;;; ARITH
  1613. ;;;;    This file provides integer arithmetic extensions.  Although
  1614. ;;;;    Emacs Lisp doesn't really support anything but integers, that
  1615. ;;;;    has still to be made to look more or less standard.
  1616. ;;;;
  1617. ;;;;
  1618. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1619. ;;;;       (quiroz@cs.rochester.edu)
  1620.  
  1621.  
  1622. (defsubst plusp (number)
  1623.   "True if NUMBER is strictly greater than zero."
  1624.   (> number 0))
  1625.  
  1626. (defsubst minusp (number)
  1627.   "True if NUMBER is strictly less than zero."
  1628.   (< number 0))
  1629.  
  1630. (defsubst oddp (number)
  1631.   "True if INTEGER is not divisible by 2."
  1632.   (/= (% number 2) 0))
  1633.  
  1634. (defsubst evenp (number)
  1635.   "True if INTEGER is divisible by 2."
  1636.   (= (% number 2) 0))
  1637.  
  1638. (defsubst abs (number)
  1639.   "Return the absolute value of NUMBER."
  1640.   (if (< number 0)
  1641.       (- number)
  1642.     number))
  1643.  
  1644. (defsubst signum (number)
  1645.   "Return -1, 0 or 1 according to the sign of NUMBER."
  1646.   (cond ((< number 0)
  1647.          -1)
  1648.         ((> number 0)
  1649.          1)
  1650.         (t                              ;exactly zero
  1651.          0)))
  1652.  
  1653. (defun gcd (&rest integers)
  1654.   "Return the greatest common divisor of all the arguments.
  1655. The arguments must be integers.  With no arguments, value is zero."
  1656.   (let ((howmany (length integers)))
  1657.     (cond ((= howmany 0)
  1658.            0)
  1659.           ((= howmany 1)
  1660.            (abs (car integers)))
  1661.           ((> howmany 2)
  1662.            (apply (function gcd)
  1663.                   (cons (gcd (nth 0 integers) (nth 1 integers))
  1664.                         (nthcdr 2 integers))))
  1665.           (t                            ;howmany=2
  1666.            ;; essentially the euclidean algorithm
  1667.            (when (zerop (* (nth 0 integers) (nth 1 integers)))
  1668.              (error "a zero argument is invalid for `gcd'"))
  1669.            (do* ((absa (abs (nth 0 integers))) ; better to operate only
  1670.                  (absb (abs (nth 1 integers))) ;on positives.
  1671.                  (dd (max absa absb))   ; setup correct order for the
  1672.                  (ds (min absa absb))   ;succesive divisions.
  1673.                  ;; intermediate results
  1674.                  (q 0)
  1675.                  (r 0)
  1676.                  ;; final results
  1677.                  (done nil)             ; flag: end of iterations
  1678.                  (result 0))            ; final value
  1679.                (done result)
  1680.              (setq q (/ dd ds))
  1681.              (setq r (% dd ds))
  1682.              (cond ((zerop r) (setq done t) (setq result ds))
  1683.                    (t         (setq dd ds)  (setq ds r))))))))
  1684.  
  1685. (defun lcm (integer &rest more)
  1686.   "Return the least common multiple of all the arguments.
  1687. The arguments must be integers and there must be at least one of them."
  1688.   (let ((howmany (length more))
  1689.         (a       integer)
  1690.         (b       (nth 0 more))
  1691.         prod                            ; intermediate product
  1692.         (yetmore (nthcdr 1 more)))
  1693.     (cond ((zerop howmany)
  1694.            (abs a))
  1695.           ((> howmany 1)                ; recursive case
  1696.            (apply (function lcm)
  1697.                   (cons (lcm a b) yetmore)))
  1698.           (t                            ; base case, just 2 args
  1699.            (setq prod (* a b))
  1700.            (cond
  1701.             ((zerop prod)
  1702.              0)
  1703.             (t
  1704.              (/ (abs prod) (gcd a b))))))))
  1705.  
  1706. (defun isqrt (number)
  1707.   "Return the integer square root of NUMBER.
  1708. NUMBER must not be negative.  Result is largest integer less than or
  1709. equal to the real square root of the argument."
  1710.   ;; The method used here is essentially the Newtonian iteration
  1711.   ;;    x[n+1] <- (x[n] + Number/x[n]) / 2
  1712.   ;; suitably adapted to integer arithmetic.
  1713.   ;; Thanks to Philippe Schnoebelen <phs@lifia.imag.fr> for suggesting the
  1714.   ;; termination condition.
  1715.   (cond ((minusp number)
  1716.          (error "argument to `isqrt' (%d) must not be negative"
  1717.                 number))
  1718.         ((zerop number)
  1719.          0)
  1720.         (t                              ;so (>= number 0)
  1721.          (do* ((approx 1)               ;any positive integer will do
  1722.                (new 0)                  ;init value irrelevant
  1723.                (done nil))
  1724.              (done (if (> (* approx approx) number)
  1725.                        (- approx 1)
  1726.                      approx))
  1727.            (setq new    (/ (+ approx (/ number approx)) 2)
  1728.                  done   (or (= new approx) (= new (+ approx 1)))
  1729.                  approx new)))))
  1730.  
  1731. (defun floor (number &optional divisor)
  1732.   "Divide DIVIDEND by DIVISOR, rounding toward minus infinity.
  1733. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1734.   (cond ((and (null divisor)            ; trivial case
  1735.               (numberp number))
  1736.          (values number 0))
  1737.         (t                              ; do the division
  1738.          (multiple-value-bind
  1739.              (q r s)
  1740.              (safe-idiv number divisor)
  1741.            (cond ((zerop s)
  1742.                   (values 0 0))
  1743.                  ((plusp s)
  1744.                   (values q r))
  1745.                  (t                     ;opposite-signs case
  1746.                   (if (zerop r)
  1747.                       (values (- q) 0)
  1748.                     (let ((q (- (+ q 1))))
  1749.                       (values q (- number (* q divisor)))))))))))
  1750.  
  1751. (defun ceiling (number &optional divisor)
  1752.   "Divide DIVIDEND by DIVISOR, rounding toward plus infinity.
  1753. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1754.   (cond ((and (null divisor)            ; trivial case
  1755.               (numberp number))
  1756.          (values number 0))
  1757.         (t                              ; do the division
  1758.          (multiple-value-bind
  1759.              (q r s)
  1760.              (safe-idiv number divisor)
  1761.            (cond ((zerop s)
  1762.                   (values 0 0))
  1763.                  ((plusp s)
  1764.                   (values (+ q 1) (- r divisor)))
  1765.                  (t
  1766.                   (values (- q) (+ number (* q divisor)))))))))
  1767.  
  1768. (defun truncate (number &optional divisor)
  1769.   "Divide DIVIDEND by DIVISOR, rounding toward zero.
  1770. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1771.   (cond ((and (null divisor)            ; trivial case
  1772.               (numberp number))
  1773.          (values number 0))
  1774.         (t                              ; do the division
  1775.          (multiple-value-bind
  1776.              (q r s)
  1777.              (safe-idiv number divisor)
  1778.            (cond ((zerop s)
  1779.                   (values 0 0))
  1780.                  ((plusp s)             ;same as floor
  1781.                   (values q r))
  1782.                  (t                     ;same as ceiling
  1783.                   (values (- q) (+ number (* q divisor)))))))))
  1784.  
  1785. (defun round (number &optional divisor)
  1786.   "Divide DIVIDEND by DIVISOR, rounding to nearest integer.
  1787. DIVISOR defaults to 1.  The remainder is produced as a second value."
  1788.   (cond ((and (null divisor)            ; trivial case
  1789.               (numberp number))
  1790.          (values number 0))    
  1791.         (t                              ; do the division
  1792.          (multiple-value-bind
  1793.              (q r s)
  1794.              (safe-idiv number divisor)
  1795.            (setq r (abs r))
  1796.            ;; adjust magnitudes first, and then signs
  1797.            (let ((other-r (- (abs divisor) r)))
  1798.              (cond ((> r other-r)
  1799.                     (setq q (+ q 1)))
  1800.                    ((and (= r other-r)
  1801.                          (oddp q))
  1802.                     ;; round to even is mandatory
  1803.                     (setq q (+ q 1))))
  1804.              (setq q (* s q))
  1805.              (setq r (- number (* q divisor)))
  1806.              (values q r))))))
  1807.  
  1808. ;;; These two functions access the implementation-dependent representation of
  1809. ;;; the multiple value returns.
  1810.  
  1811. (defun mod (number divisor)
  1812.   "Return remainder of X by Y (rounding quotient toward minus infinity).
  1813. That is, the remainder goes with the quotient produced by `floor'.
  1814. Emacs Lisp hint:
  1815. If you know that both arguments are positive, use `%' instead for speed."
  1816.   (floor number divisor)
  1817.   (cadr *mvalues-values*))
  1818.  
  1819. (defun rem (number divisor)
  1820.   "Return remainder of X by Y (rounding quotient toward zero).
  1821. That is, the remainder goes with the quotient produced by `truncate'.
  1822. Emacs Lisp hint:
  1823. If you know that both arguments are positive, use `%' instead for speed."
  1824.   (truncate number divisor)
  1825.   (cadr *mvalues-values*))
  1826.  
  1827. ;;; internal utilities
  1828. ;;;
  1829. ;;; safe-idiv performs an integer division with positive numbers only.
  1830. ;;; It is known that some machines/compilers implement weird remainder
  1831. ;;; computations when working with negatives, so the idea here is to
  1832. ;;; make sure we know what is coming back to the caller in all cases.
  1833.  
  1834. ;;; Signum computation fixed by mad@math.keio.JUNET (MAEDA Atusi)
  1835.  
  1836. (defun safe-idiv (a b)
  1837.   "SAFE-IDIV A B => Q R S
  1838. Q=|A|/|B|, S is the sign of A/B, R is the rest A - S*Q*B."
  1839.   ;; (unless (and (numberp a) (numberp b))
  1840.   ;;   (error "arguments to `safe-idiv' must be numbers"))
  1841.   ;; (when (zerop b)
  1842.   ;;   (error "cannot divide %d by zero" a))
  1843.   (let* ((q (/ (abs a) (abs b)))
  1844.          (s (* (signum a) (signum b)))
  1845.          (r (- a (* s q b))))
  1846.     (values q r s)))
  1847.  
  1848. ;;;; end of cl-arith.el
  1849.  
  1850. ;;;; SETF
  1851. ;;;;    This file provides the setf macro and friends. The purpose has
  1852. ;;;;    been modest, only the simplest defsetf forms are accepted.
  1853. ;;;;    Use it and enjoy.
  1854. ;;;;
  1855. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  1856. ;;;;       (quiroz@cs.rochester.edu)
  1857.  
  1858.  
  1859. (defkeyword :setf-update-fn
  1860.   "Property, its value is the function setf must invoke to update a
  1861. generalized variable whose access form is a function call of the
  1862. symbol that has this property.")
  1863.  
  1864. (defkeyword :setf-update-doc
  1865.   "Property of symbols that have a `defsetf' update function on them,
  1866. installed by the `defsetf' from its optional third argument.")
  1867.  
  1868. (defmacro setf (&rest pairs)
  1869.   "Generalized `setq' that can set things other than variable values.
  1870. A use of `setf' looks like (setf {PLACE VALUE}...).
  1871. The behavior of (setf PLACE VALUE) is to access the generalized variable
  1872. at PLACE and store VALUE there.  It returns VALUE.  If there is more
  1873. than one PLACE and VALUE, each PLACE is set from its VALUE before
  1874. the next PLACE is evaluated."
  1875.   (let ((nforms (length pairs)))
  1876.     ;; check the number of subforms
  1877.     (cond ((/= (% nforms 2) 0)
  1878.            (error "odd number of arguments to `setf'"))
  1879.           ((= nforms 0)
  1880.            nil)
  1881.           ((> nforms 2)
  1882.            ;; this is the recursive case
  1883.            (cons 'progn
  1884.                  (do*                   ;collect the place-value pairs
  1885.                      ((args pairs (cddr args))
  1886.                       (place (car args) (car args))
  1887.                       (value (cadr args) (cadr args))
  1888.                       (result '()))
  1889.                      ((endp args) (nreverse result))
  1890.                    (setq result
  1891.                          (cons (list 'setf place value)
  1892.                                result)))))
  1893.           (t                            ;i.e., nforms=2
  1894.            ;; this is the base case (SETF PLACE VALUE)
  1895.            (let* ((place (car pairs))
  1896.                   (value (cadr pairs))
  1897.                   (head  nil)
  1898.                   (updatefn nil))
  1899.              ;; dispatch on the type of the PLACE
  1900.              (cond ((symbolp place)
  1901.                     (list 'setq place value))
  1902.                    ((and (listp place)
  1903.                          (setq head (car place))
  1904.                          (symbolp head)
  1905.                          (setq updatefn (get head :setf-update-fn)))
  1906.                     ;; dispatch on the type of update function
  1907.             (cond ((and (consp updatefn) (eq (car updatefn) 'lambda))
  1908.                (cons 'funcall
  1909.                  (cons (list 'function updatefn)
  1910.                        (append (cdr place) (list value)))))
  1911.               ((and (symbolp updatefn)
  1912.                                 (fboundp updatefn)
  1913.                                 (let ((defn (symbol-function updatefn)))
  1914.                                   (or (subrp defn)
  1915.                                       (and (consp defn)
  1916.                        (or (eq (car defn) 'lambda)
  1917.                            (eq (car defn) 'macro))))))
  1918.                (cons updatefn (append (cdr place) (list value))))
  1919.               (t
  1920.                            (multiple-value-bind
  1921.                                (bindings newsyms)
  1922.                                (pair-with-newsyms
  1923.                                 (append (cdr place) (list value)))
  1924.                              ;; this let gets new symbols to ensure adequate 
  1925.                              ;; order of evaluation of the subforms.
  1926.                              (list 'let
  1927.                                    bindings              
  1928.                                    (cons updatefn newsyms))))))
  1929.                    (t
  1930.                     (error "no `setf' update-function for `%s'"
  1931.                            (prin1-to-string place)))))))))
  1932.  
  1933. (defmacro defsetf (accessfn updatefn &optional docstring)
  1934.   "Define how `setf' works on a certain kind of generalized variable.
  1935. A use of `defsetf' looks like (defsetf ACCESSFN UPDATEFN [DOCSTRING]).
  1936. ACCESSFN is a symbol.  UPDATEFN is a function or macro which takes
  1937. one more argument than ACCESSFN does.  DEFSETF defines the translation
  1938. of (SETF (ACCESFN . ARGS) NEWVAL) to be a form like (UPDATEFN ARGS... NEWVAL).
  1939. The function UPDATEFN must return its last arg, after performing the
  1940. updating called for."
  1941.   ;; reject ill-formed requests.  too bad one can't test for functionp
  1942.   ;; or macrop.
  1943.   (when (not (symbolp accessfn))
  1944.     (error "first argument of `defsetf' must be a symbol, not `%s'"
  1945.            (prin1-to-string accessfn)))
  1946.   ;; update properties
  1947.   (list 'progn
  1948.         (list 'put (list 'quote accessfn)
  1949.               :setf-update-fn (list 'function updatefn))
  1950.         (list 'put (list 'quote accessfn) :setf-update-doc docstring)
  1951.         ;; any better thing to return?
  1952.         (list 'quote accessfn)))
  1953.  
  1954. ;;; This section provides the "default" setfs for Common-Emacs-Lisp
  1955. ;;; The user will not normally add anything to this, although
  1956. ;;; defstruct will introduce new ones as a matter of fact.
  1957. ;;;
  1958. ;;; Apply is a special case.   The Common Lisp
  1959. ;;; standard makes the case of apply be useful when the user writes
  1960. ;;; something like (apply #'name ...), Emacs Lisp doesn't have the #
  1961. ;;; stuff, but it has (function ...).  Notice that V18 includes a new
  1962. ;;; apply: this file is compatible with V18 and pre-V18 Emacses.
  1963.  
  1964. ;;; INCOMPATIBILITY: the SETF macro evaluates its arguments in the
  1965. ;;; (correct) left to right sequence *before* checking for apply
  1966. ;;; methods (which should really be an special case inside setf).  Due
  1967. ;;; to this, the lambda expression defsetf'd to apply will succeed in
  1968. ;;; applying the right function even if the name was not quoted, but
  1969. ;;; computed!  That extension is not Common Lisp (nor is particularly
  1970. ;;; useful, I think).
  1971.  
  1972. (defsetf apply
  1973.   (lambda (&rest args)
  1974.     ;; dissasemble the calling form
  1975.     ;; "(((quote fn) x1 x2 ... xn) val)" (function instead of quote, too)
  1976.     (let* ((fnform (car args))          ;functional form
  1977.            (applyargs (append           ;arguments "to apply fnform"
  1978.                        (apply 'list* (butlast (cdr args)))
  1979.                        (last args)))
  1980.            (newupdater nil))            ; its update-fn, if any
  1981.       (if (and (symbolp fnform)
  1982.                (setq newupdater (get fnform :setf-update-fn)))
  1983.           (apply  newupdater applyargs)
  1984.         (error "can't `setf' to `%s'"
  1985.                (prin1-to-string fnform)))))
  1986.   "`apply' is a special case for `setf'")
  1987.  
  1988.  
  1989. (defsetf aref
  1990.   aset
  1991.   "`setf' inversion for `aref'")
  1992.  
  1993. (defsetf nth
  1994.   setnth
  1995.   "`setf' inversion for `nth'")
  1996.  
  1997. (defsetf nthcdr
  1998.   setnthcdr
  1999.   "`setf' inversion for `nthcdr'")
  2000.  
  2001. (defsetf elt
  2002.   setelt
  2003.   "`setf' inversion for `elt'")
  2004.  
  2005. (defsetf first
  2006.   (lambda (list val) (setnth 0 list val))
  2007.   "`setf' inversion for `first'")
  2008.  
  2009. (defsetf second
  2010.   (lambda (list val) (setnth 1 list val))
  2011.   "`setf' inversion for `second'")
  2012.  
  2013. (defsetf third
  2014.   (lambda (list val) (setnth 2 list val))
  2015.   "`setf' inversion for `third'")
  2016.  
  2017. (defsetf fourth
  2018.   (lambda (list val) (setnth 3 list val))
  2019.   "`setf' inversion for `fourth'")
  2020.  
  2021. (defsetf fifth
  2022.   (lambda (list val) (setnth 4 list val))
  2023.   "`setf' inversion for `fifth'")
  2024.  
  2025. (defsetf sixth
  2026.   (lambda (list val) (setnth 5 list val))
  2027.   "`setf' inversion for `sixth'")
  2028.  
  2029. (defsetf seventh
  2030.   (lambda (list val) (setnth 6 list val))
  2031.   "`setf' inversion for `seventh'")
  2032.  
  2033. (defsetf eighth
  2034.   (lambda (list val) (setnth 7 list val))
  2035.   "`setf' inversion for `eighth'")
  2036.  
  2037. (defsetf ninth
  2038.   (lambda (list val) (setnth 8 list val))
  2039.   "`setf' inversion for `ninth'")
  2040.  
  2041. (defsetf tenth
  2042.   (lambda (list val) (setnth 9 list val))
  2043.   "`setf' inversion for `tenth'")
  2044.  
  2045. (defsetf rest
  2046.   (lambda (list val) (setcdr list val))
  2047.   "`setf' inversion for `rest'")
  2048.  
  2049. (defsetf car setcar "Replace the car of a cons")
  2050.  
  2051. (defsetf cdr setcdr "Replace the cdr of a cons")
  2052.  
  2053. (defsetf caar
  2054.   (lambda (list val) (setcar (nth 0 list) val))
  2055.   "`setf' inversion for `caar'")
  2056.  
  2057. (defsetf cadr
  2058.   (lambda (list val) (setcar (cdr list) val))
  2059.   "`setf' inversion for `cadr'")
  2060.  
  2061. (defsetf cdar
  2062.   (lambda (list val) (setcdr (car list) val))
  2063.   "`setf' inversion for `cdar'")
  2064.  
  2065. (defsetf cddr
  2066.   (lambda (list val) (setcdr (cdr list) val))
  2067.   "`setf' inversion for `cddr'")
  2068.  
  2069. (defsetf caaar
  2070.   (lambda (list val) (setcar (caar list) val))
  2071.   "`setf' inversion for `caaar'")
  2072.  
  2073. (defsetf caadr
  2074.   (lambda (list val) (setcar (cadr list) val))
  2075.   "`setf' inversion for `caadr'")
  2076.  
  2077. (defsetf cadar
  2078.   (lambda (list val) (setcar (cdar list) val))
  2079.   "`setf' inversion for `cadar'")
  2080.  
  2081. (defsetf cdaar
  2082.   (lambda (list val) (setcdr (caar list) val))
  2083.   "`setf' inversion for `cdaar'")
  2084.  
  2085. (defsetf caddr
  2086.   (lambda (list val) (setcar (cddr list) val))
  2087.   "`setf' inversion for `caddr'")
  2088.  
  2089. (defsetf cdadr
  2090.   (lambda (list val) (setcdr (cadr list) val))
  2091.   "`setf' inversion for `cdadr'")
  2092.  
  2093. (defsetf cddar
  2094.   (lambda (list val) (setcdr (cdar list) val))
  2095.   "`setf' inversion for `cddar'")
  2096.  
  2097. (defsetf cdddr
  2098.   (lambda (list val) (setcdr (cddr list) val))
  2099.   "`setf' inversion for `cdddr'")
  2100.  
  2101. (defsetf caaaar
  2102.   (lambda (list val) (setcar (caaar list) val))
  2103.   "`setf' inversion for `caaaar'")
  2104.  
  2105. (defsetf caaadr
  2106.   (lambda (list val) (setcar (caadr list) val))
  2107.   "`setf' inversion for `caaadr'")
  2108.  
  2109. (defsetf caadar
  2110.   (lambda (list val) (setcar (cadar list) val))
  2111.   "`setf' inversion for `caadar'")
  2112.  
  2113. (defsetf cadaar
  2114.   (lambda (list val) (setcar (cdaar list) val))
  2115.   "`setf' inversion for `cadaar'")
  2116.  
  2117. (defsetf cdaaar
  2118.   (lambda (list val) (setcdr (caar list) val))
  2119.   "`setf' inversion for `cdaaar'")
  2120.  
  2121. (defsetf caaddr
  2122.   (lambda (list val) (setcar (caddr list) val))
  2123.   "`setf' inversion for `caaddr'")
  2124.  
  2125. (defsetf cadadr
  2126.   (lambda (list val) (setcar (cdadr list) val))
  2127.   "`setf' inversion for `cadadr'")
  2128.  
  2129. (defsetf cdaadr
  2130.   (lambda (list val) (setcdr (caadr list) val))
  2131.   "`setf' inversion for `cdaadr'")
  2132.  
  2133. (defsetf caddar
  2134.   (lambda (list val) (setcar (cddar list) val))
  2135.   "`setf' inversion for `caddar'")
  2136.  
  2137. (defsetf cdadar
  2138.   (lambda (list val) (setcdr (cadar list) val))
  2139.   "`setf' inversion for `cdadar'")
  2140.  
  2141. (defsetf cddaar
  2142.   (lambda (list val) (setcdr (cdaar list) val))
  2143.   "`setf' inversion for `cddaar'")
  2144.  
  2145. (defsetf cadddr
  2146.   (lambda (list val) (setcar (cdddr list) val))
  2147.   "`setf' inversion for `cadddr'")
  2148.  
  2149. (defsetf cddadr
  2150.   (lambda (list val) (setcdr (cdadr list) val))
  2151.   "`setf' inversion for `cddadr'")
  2152.  
  2153. (defsetf cdaddr
  2154.   (lambda (list val) (setcdr (caddr list) val))
  2155.   "`setf' inversion for `cdaddr'")
  2156.  
  2157. (defsetf cdddar
  2158.   (lambda (list val) (setcdr (cddar list) val))
  2159.   "`setf' inversion for `cdddar'")
  2160.  
  2161. (defsetf cddddr
  2162.   (lambda (list val) (setcdr (cddr list) val))
  2163.   "`setf' inversion for `cddddr'")
  2164.  
  2165. (defsetf get put "`setf' inversion for `get' is `put'")
  2166.  
  2167. (defsetf symbol-function fset
  2168.   "`setf' inversion for `symbol-function' is `fset'")
  2169.  
  2170. (defsetf symbol-plist setplist
  2171.   "`setf' inversion for `symbol-plist' is `setplist'")
  2172.  
  2173. (defsetf symbol-value set
  2174.   "`setf' inversion for `symbol-value' is `set'")
  2175.  
  2176. (defsetf point goto-char
  2177.   "To set (point) to N, use (goto-char N)")
  2178.  
  2179. ;; how about defsetfing other Emacs forms?
  2180.  
  2181. ;;; Modify macros
  2182. ;;;
  2183. ;;; It could be nice to implement define-modify-macro, but I don't
  2184. ;;; think it really pays.
  2185.  
  2186. (defmacro incf (ref &optional delta)
  2187.   "(incf REF [DELTA]) -> increment the g.v. REF by DELTA (default 1)"
  2188.   (if (null delta)
  2189.       (setq delta 1))
  2190.   (list 'setf ref (list '+ ref delta)))
  2191.  
  2192. (defmacro decf (ref &optional delta)
  2193.   "(decf REF [DELTA]) -> decrement the g.v. REF by DELTA (default 1)"
  2194.   (if (null delta)
  2195.       (setq delta 1))
  2196.   (list 'setf ref (list '- ref delta)))
  2197.  
  2198. (defmacro push (item ref)
  2199.   "(push ITEM REF) -> cons ITEM at the head of the g.v. REF (a list)"
  2200.   (list 'setf ref (list 'cons item ref)))
  2201.  
  2202. (defmacro pushnew (item ref)
  2203.   "(pushnew ITEM REF): adjoin ITEM at the head of the g.v. REF (a list)"
  2204.   (list 'setf ref (list 'adjoin item ref)))
  2205.  
  2206. (defmacro pop (ref)
  2207.   "(pop REF) -> (prog1 (car REF) (setf REF (cdr REF)))"
  2208.   (let ((listname (gensym)))
  2209.     (list 'let (list (list listname ref))
  2210.           (list 'prog1
  2211.                 (list 'car listname)
  2212.                 (list 'setf ref (list 'cdr listname))))))
  2213.  
  2214. ;;; PSETF
  2215. ;;;
  2216. ;;; Psetf is the generalized variable equivalent of psetq.  The right
  2217. ;;; hand sides are evaluated and assigned (via setf) to the left hand
  2218. ;;; sides. The evaluations are done in an environment where they
  2219. ;;; appear to occur in parallel.
  2220.  
  2221. (defmacro psetf (&rest body)
  2222.   "(psetf {var value }...) => nil
  2223. Like setf, but all the values are computed before any assignment is made."
  2224.   (let ((length (length body)))
  2225.     (cond ((/= (% length 2) 0)
  2226.            (error "psetf needs an even number of arguments, %d given"
  2227.                   length))
  2228.           ((null body)
  2229.            '())
  2230.           (t
  2231.            (list 'prog1 nil
  2232.                  (let ((setfs     '())
  2233.                        (bodyforms (reverse body)))
  2234.                    (while bodyforms
  2235.                      (let* ((value (car bodyforms))
  2236.                             (place (cadr bodyforms)))
  2237.                        (setq bodyforms (cddr bodyforms))
  2238.                        (if (null setfs)
  2239.                            (setq setfs (list 'setf place value))
  2240.                          (setq setfs (list 'setf place
  2241.                                            (list 'prog1 value
  2242.                                                  setfs))))))
  2243.                    setfs))))))
  2244.  
  2245. ;;; SHIFTF and ROTATEF 
  2246. ;;;
  2247.  
  2248. (defmacro shiftf (&rest forms)
  2249.   "(shiftf PLACE1 PLACE2... NEWVALUE)
  2250. Set PLACE1 to PLACE2, PLACE2 to PLACE3...
  2251. Each PLACE is set to the old value of the following PLACE,
  2252. and the last PLACE is set to the value NEWVALUE.  
  2253. Returns the old value of PLACE1."
  2254.   (unless (> (length forms) 1)
  2255.     (error "`shiftf' needs more than one argument"))
  2256.   (let ((places (butlast forms))
  2257.     (newvalue (car (last forms))))
  2258.     ;; the places are accessed to fresh symbols
  2259.     (multiple-value-bind
  2260.     (bindings newsyms)
  2261.     (pair-with-newsyms places)
  2262.       (list 'let bindings
  2263.         (cons 'setf
  2264.           (zip-lists places
  2265.                  (append (cdr newsyms) (list newvalue))))
  2266.         (car newsyms)))))
  2267.  
  2268. (defmacro rotatef (&rest places)
  2269.   "(rotatef PLACE...) sets each PLACE to the old value of the following PLACE.
  2270. The last PLACE is set to the old value of the first PLACE.
  2271. Thus, the values rotate through the PLACEs.  Returns nil."
  2272.   (if (null places)
  2273.       nil
  2274.    (multiple-value-bind
  2275.        (bindings newsyms)
  2276.        (pair-with-newsyms places)
  2277.      (list
  2278.       'let bindings
  2279.       (cons 'setf
  2280.             (zip-lists places
  2281.                        (append (cdr newsyms) (list (car newsyms)))))
  2282.       nil))))
  2283.  
  2284. ;;; GETF, REMF, and REMPROP
  2285. ;;;
  2286.  
  2287. (defun getf (place indicator &optional default)
  2288.   "Return PLACE's PROPNAME property, or DEFAULT if not present."
  2289.   (while (and place (not (eq (car place) indicator)))
  2290.     (setq place (cdr (cdr place))))
  2291.   (if place
  2292.       (car (cdr place))
  2293.     default))
  2294.  
  2295. (defmacro getf$setf$method (place indicator default &rest newval)
  2296.   "SETF method for GETF.  Not for public use."
  2297.   (case (length newval)
  2298.     (0 (setq newval default default nil))
  2299.     (1 (setq newval (car newval)))
  2300.     (t (error "Wrong number of arguments to (setf (getf ...)) form")))
  2301.   (let ((psym (gentemp)) (isym (gentemp)) (vsym (gentemp)))
  2302.     (list 'let (list (list psym place)
  2303.              (list isym indicator)
  2304.              (list vsym newval))
  2305.       (list 'while
  2306.         (list 'and psym
  2307.               (list 'not
  2308.                 (list 'eq (list 'car psym) isym)))
  2309.         (list 'setq psym (list 'cdr (list 'cdr psym))))
  2310.       (list 'if psym
  2311.         (list 'setcar (list 'cdr psym) vsym)
  2312.         (list 'setf place
  2313.               (list 'nconc place (list 'list isym newval))))
  2314.       vsym)))
  2315.  
  2316. (defsetf getf
  2317.   getf$setf$method)
  2318.  
  2319. (defmacro remf (place indicator)
  2320.   "Remove from the property list at PLACE its PROPNAME property.
  2321. Returns non-nil if and only if the property existed."
  2322.   (let ((psym (gentemp)) (isym (gentemp)))
  2323.     (list 'let (list (list psym place) (list isym indicator))
  2324.       (list 'cond
  2325.         (list (list 'eq isym (list 'car psym))
  2326.               (list 'setf place (list 'cdr (list 'cdr psym)))
  2327.               t)
  2328.         (list t
  2329.               (list 'setq psym (list 'cdr psym))
  2330.               (list 'while
  2331.                 (list 'and (list 'cdr psym)
  2332.                   (list 'not
  2333.                     (list 'eq (list 'car (list 'cdr psym))
  2334.                           isym)))
  2335.                 (list 'setq psym (list 'cdr (list 'cdr psym))))
  2336.               (list 'cond
  2337.                 (list (list 'cdr psym)
  2338.                   (list 'setcdr psym
  2339.                     (list 'cdr
  2340.                           (list 'cdr (list 'cdr psym))))
  2341.                   t)))))))
  2342.  
  2343. (defun remprop (symbol indicator)
  2344.   "Remove SYMBOL's PROPNAME property, returning non-nil if it was present."
  2345.   (remf (symbol-plist symbol) indicator))
  2346.   
  2347.  
  2348. ;;;; STRUCTS
  2349. ;;;;    This file provides the structures mechanism.  See the
  2350. ;;;;    documentation for Common-Lisp's defstruct.  Mine doesn't
  2351. ;;;;    implement all the functionality of the standard, although some
  2352. ;;;;    more could be grafted if so desired.  More details along with
  2353. ;;;;    the code.
  2354. ;;;;
  2355. ;;;;
  2356. ;;;;    Cesar Quiroz @ UofR DofCSc - Dec. 1986
  2357. ;;;;       (quiroz@cs.rochester.edu)
  2358.  
  2359.  
  2360. (defkeyword :include             "Syntax of `defstruct'")
  2361. (defkeyword :named               "Syntax of `defstruct'")
  2362. (defkeyword :conc-name           "Syntax of `defstruct'")
  2363. (defkeyword :copier              "Syntax of `defstruct'")
  2364. (defkeyword :predicate           "Syntax of `defstruct'")
  2365. (defkeyword :print-function      "Syntax of `defstruct'")
  2366. (defkeyword :type                "Syntax of `defstruct'")
  2367. (defkeyword :initial-offset      "Syntax of `defstruct'")
  2368.  
  2369. (defkeyword :structure-doc       "Documentation string for a structure.")
  2370. (defkeyword :structure-slotsn    "Number of slots in structure")
  2371. (defkeyword :structure-slots     "List of the slot's names")
  2372. (defkeyword :structure-indices   "List of (KEYWORD-NAME . INDEX)")
  2373. (defkeyword :structure-initforms "List of (KEYWORD-NAME . INITFORM)")
  2374. (defkeyword :structure-includes
  2375.             "() or list of a symbol, that this struct includes")
  2376. (defkeyword :structure-included-in
  2377.             "List of the structs that include this")
  2378.  
  2379.  
  2380. (defmacro defstruct (&rest args)
  2381.   "(defstruct NAME [DOC-STRING] . SLOTS)  define NAME as structure type.
  2382. NAME must be a symbol, the name of the new structure.  It could also
  2383. be a list (NAME . OPTIONS).  
  2384.  
  2385. Each option is either a symbol, or a list of a keyword symbol taken from the
  2386. list \{:conc-name, :copier, :constructor, :predicate, :include,
  2387. :print-function, :type, :initial-offset\}.  The meanings of these are as in
  2388. CLtL, except that no BOA-constructors are provided, and the options
  2389. \{:print-fuction, :type, :initial-offset\} are ignored quietly.  All these
  2390. structs are named, in the sense that their names can be used for type
  2391. discrimination.
  2392.  
  2393. The DOC-STRING is established as the `structure-doc' property of NAME.
  2394.  
  2395. The SLOTS are one or more of the following:
  2396. SYMBOL -- meaning the SYMBOL is the name of a SLOT of NAME
  2397. list of SYMBOL and VALUE -- meaning that VALUE is the initial value of
  2398. the slot.
  2399. `defstruct' defines functions `make-NAME', `NAME-p', `copy-NAME' for the
  2400. structure, and functions with the same name as the slots to access
  2401. them.  `setf' of the accessors sets their values."
  2402.   (multiple-value-bind
  2403.       (name options docstring slotsn slots initlist)
  2404.       (parse$defstruct$args args)
  2405.     ;; Names for the member functions come from the options.  The
  2406.     ;; slots* stuff collects info about the slots declared explicitly. 
  2407.     (multiple-value-bind
  2408.         (conc-name constructor copier predicate
  2409.          moreslotsn moreslots moreinits included)
  2410.         (parse$defstruct$options name options slots)
  2411.       ;; The moreslots* stuff refers to slots gained as a consequence
  2412.       ;; of (:include clauses). -- Oct 89:  Only one :include tolerated
  2413.       (when (and (numberp moreslotsn)
  2414.                  (> moreslotsn 0))
  2415.         (setf slotsn (+ slotsn moreslotsn))
  2416.         (setf slots (append moreslots slots))
  2417.         (setf initlist (append moreinits initlist)))
  2418.       (unless (> slotsn 0)
  2419.         (error "%s needs at least one slot"
  2420.                (prin1-to-string name)))
  2421.       (let ((dups (duplicate-symbols-p slots)))
  2422.         (when dups
  2423.           (error "`%s' are duplicates"
  2424.                  (prin1-to-string dups))))
  2425.       (setq initlist (simplify$inits slots initlist))
  2426.       (let (properties functions keywords accessors alterators returned)
  2427.         ;; compute properties of NAME
  2428.         (setq properties
  2429.               (append
  2430.                (list
  2431.                 (list 'put (list 'quote name) :structure-doc
  2432.                       docstring)
  2433.                 (list 'put (list 'quote name) :structure-slotsn
  2434.                       slotsn)
  2435.                 (list 'put (list 'quote name) :structure-slots
  2436.                       (list 'quote slots))
  2437.                 (list 'put (list 'quote name) :structure-initforms
  2438.                       (list 'quote initlist))
  2439.                 (list 'put (list 'quote name) :structure-indices
  2440.                       (list 'quote (extract$indices initlist))))
  2441.                ;; If this definition :includes another defstruct,
  2442.                ;; modify both property lists.
  2443.                (cond (included
  2444.                       (list
  2445.                        (list 'put
  2446.                              (list 'quote name)
  2447.                              :structure-includes
  2448.                              (list 'quote included))
  2449.                        (list 'pushnew
  2450.                              (list 'quote name)
  2451.                              (list 'get (list 'quote (car included))
  2452.                                    :structure-included-in))))
  2453.                      (t
  2454.                       (list
  2455.                        (let ((old (gensym)))
  2456.                          (list 'let 
  2457.                                (list (list old
  2458.                                            (list 'car
  2459.                                                  (list 'get
  2460.                                                        (list 'quote name)
  2461.                                                        :structure-includes))))
  2462.                                (list 'when old
  2463.                                      (list 'put
  2464.                                            old
  2465.                                            :structure-included-in
  2466.                                            (list 'delq
  2467.                                                  (list 'quote name)
  2468.                                                  ;; careful with destructive
  2469.                                                  ;;manipulation!
  2470.                                                  (list
  2471.                                                   'append
  2472.                                                   (list
  2473.                                                    'get
  2474.                                                    old
  2475.                                                    :structure-included-in)
  2476.                                                   '())
  2477.                                                  )))))
  2478.                        (list 'put
  2479.                              (list 'quote name)
  2480.                              :structure-includes
  2481.                              '()))))
  2482.                ;; If this definition used to be :included in another, warn
  2483.                ;; that things make break.  On the other hand, the redefinition
  2484.                ;; may be trivial, so don't call it an error.
  2485.                (let ((old (gensym)))
  2486.                  (list
  2487.                   (list 'let
  2488.                         (list (list old (list 'get
  2489.                                               (list 'quote name)
  2490.                                               :structure-included-in)))
  2491.                         (list 'when old
  2492.                               (list 'message
  2493.                                     "`%s' redefined.  Should redefine `%s'?"
  2494.                                     (list 'quote name)
  2495.                                     (list 'prin1-to-string old))))))))
  2496.  
  2497.         ;; Compute functions associated with NAME.  This is not
  2498.     ;; handling BOA constructors yet, but here would be the place.
  2499.         (setq functions
  2500.               (list
  2501.                (list 'fset (list 'quote constructor)
  2502.                      (list 'function
  2503.                            (list 'lambda (list '&rest 'args)
  2504.                                  (list 'make$structure$instance
  2505.                                        (list 'quote name)
  2506.                                        'args))))
  2507.                (list 'fset (list 'quote copier)
  2508.                      (list 'function 'copy-sequence))
  2509.                (let ((typetag (gensym)))
  2510.                  (list 'fset (list 'quote predicate)
  2511.                        (list 
  2512.                         'function
  2513.                         (list 
  2514.                          'lambda (list 'thing)
  2515.                          (list 'and
  2516.                                (list 'vectorp 'thing)
  2517.                                (list 'let
  2518.                                      (list (list typetag
  2519.                                                  (list 'elt 'thing 0)))
  2520.                                      (list 'or
  2521.                                            (list
  2522.                                             'and
  2523.                                             (list 'eq
  2524.                                                   typetag
  2525.                                                   (list 'quote name))
  2526.                                             (list '=
  2527.                                                   (list 'length 'thing)
  2528.                                                   (1+ slotsn)))
  2529.                                            (list
  2530.                                             'memq
  2531.                                             typetag
  2532.                                             (list 'get
  2533.                                                   (list 'quote name)
  2534.                                                   :structure-included-in))))))
  2535.                         )))))
  2536.         ;; compute accessors for NAME's slots
  2537.         (multiple-value-setq
  2538.             (accessors alterators keywords)
  2539.             (build$accessors$for name conc-name predicate slots slotsn))
  2540.         ;; generate returned value -- not defined by the standard
  2541.         (setq returned
  2542.               (list
  2543.                (cons 'vector
  2544.                      (mapcar
  2545.                       (function (lambda (x) (list 'quote x)))
  2546.                       (cons name slots)))))
  2547.         ;; generate code
  2548.         (cons 'progn
  2549.               (nconc properties functions keywords
  2550.                      accessors alterators returned))))))
  2551.  
  2552. (defun parse$defstruct$args (args)
  2553.   "(parse$defstruct$args ARGS) => NAME OPTIONS DOCSTRING SLOTSN SLOTS INITLIST
  2554. NAME=symbol, OPTIONS=list of, DOCSTRING=string, SLOTSN=count of slots,
  2555. SLOTS=list of their names, INITLIST=alist (keyword . initform)."
  2556.   (let (name                            ;args=(symbol...) or ((symbol...)...)
  2557.         options                         ;args=((symbol . options) ...)
  2558.         (docstring "")                  ;args=(head docstring . slotargs)
  2559.         slotargs                        ;second or third cdr of args
  2560.         (slotsn 0)                      ;number of slots 
  2561.         (slots '())                     ;list of slot names
  2562.         (initlist '()))                 ;list of (slot keyword . initform)
  2563.     ;; extract name and options
  2564.     (cond ((symbolp (car args))         ;simple name
  2565.            (setq name    (car args)
  2566.                  options '()))
  2567.           ((and (listp   (car args))    ;(name . options)
  2568.                 (symbolp (caar args)))
  2569.            (setq name    (caar args)
  2570.                  options (cdar args)))
  2571.           (t
  2572.            (error "first arg to `defstruct' must be symbol or (symbol ...)")))
  2573.     (setq slotargs (cdr args))
  2574.     ;; is there a docstring?
  2575.     (when (stringp (car slotargs))
  2576.       (setq docstring (car slotargs)
  2577.             slotargs  (cdr slotargs)))
  2578.     ;; now for the slots
  2579.     (multiple-value-bind
  2580.         (slotsn slots initlist)
  2581.         (process$slots slotargs)
  2582.       (values name options docstring slotsn slots initlist))))
  2583.  
  2584. (defun process$slots (slots)
  2585.   "(process$slots SLOTS) => SLOTSN SLOTSLIST INITLIST
  2586. Converts a list of symbols or lists of symbol and form into the last 3
  2587. values returned by PARSE$DEFSTRUCT$ARGS."
  2588.   (let ((slotsn (length slots))         ;number of slots
  2589.         slotslist                       ;(slot1 slot2 ...)
  2590.         initlist)                       ;((:slot1 . init1) ...)
  2591.     (do*
  2592.         ((ptr  slots     (cdr ptr))
  2593.          (this (car ptr) (car ptr)))
  2594.         ((endp ptr))
  2595.       (cond ((symbolp this)
  2596.              (setq slotslist (cons this slotslist))
  2597.              (setq initlist (acons (keyword-of this) nil initlist)))
  2598.             ((and (listp this)
  2599.                   (symbolp (car this)))
  2600.              (let ((name (car this))
  2601.                    (form (cadr this)))
  2602.                ;; this silently ignores any slot options.  bad...
  2603.                (setq slotslist (cons name slotslist))
  2604.                (setq initlist  (acons (keyword-of name) form initlist))))
  2605.             (t
  2606.              (error "slot should be symbol or (symbol ...), not `%s'"
  2607.                     (prin1-to-string this)))))
  2608.     (values slotsn (nreverse slotslist) (nreverse initlist))))
  2609.  
  2610. (defun parse$defstruct$options (name options slots)
  2611.   "(parse$defstruct$options name OPTIONS SLOTS) => many values
  2612. A defstruct named NAME, with options list OPTIONS, has already slots SLOTS.
  2613. Parse the OPTIONS and return the updated form of the struct's slots and other
  2614. information.  The values returned are:
  2615.  
  2616.    CONC-NAME is the string to use as prefix/suffix in the methods,
  2617.    CONST is the name of the official constructor,
  2618.    COPIER is the name of the structure copier,
  2619.    PRED is the name of the type predicate,
  2620.    MORESLOTSN is the number of slots added by :include,
  2621.    MORESLOTS is the list of slots added by :include,
  2622.    MOREINITS is the list of initialization forms added by :include,
  2623.    INCLUDED is nil, or the list of the symbol added by :include"
  2624.   (let* ((namestring (symbol-name name))
  2625.          ;; to build the return values
  2626.          (conc-name  (concat namestring "-"))
  2627.          (const (intern (concat "make-" namestring)))
  2628.          (copier (intern (concat "copy-" namestring)))
  2629.          (pred (intern (concat namestring "-p")))
  2630.          (moreslotsn 0)
  2631.          (moreslots '())
  2632.          (moreinits '())
  2633.          ;; auxiliaries
  2634.          option-head                    ;When an option is not a plain
  2635.          option-second                  ; keyword, it must be a list of
  2636.          option-rest                    ; the form (head second . rest)
  2637.          these-slotsn                   ;When :include is found, the
  2638.          these-slots                    ; info about the included
  2639.          these-inits                    ; structure is added here.
  2640.          included                       ;NIL or (list INCLUDED)
  2641.          )
  2642.     ;; Values above are the defaults.  Now we read the options themselves
  2643.     (dolist (option options)
  2644.       ;; 2 cases arise, as options must be a keyword or a list
  2645.       (cond
  2646.        ((keywordp option)
  2647.         (case option
  2648.           (:named
  2649.            )                            ;ignore silently
  2650.           (t
  2651.            (error "can't recognize option `%s'"
  2652.                   (prin1-to-string option)))))
  2653.        ((and (listp option)
  2654.              (keywordp (setq option-head (car option))))
  2655.         (setq option-second (second option))
  2656.         (setq option-rest   (nthcdr 2 option))
  2657.         (case option-head
  2658.           (:conc-name
  2659.            (setq conc-name
  2660.                  (cond
  2661.                   ((stringp option-second)
  2662.                    option-second)
  2663.                   ((null option-second)
  2664.                    "")
  2665.                   (t
  2666.                    (error "`%s' is invalid as `conc-name'"
  2667.                           (prin1-to-string option-second))))))
  2668.           (:copier
  2669.            (setq copier
  2670.                  (cond
  2671.                   ((and (symbolp option-second)
  2672.                         (null option-rest))
  2673.                    option-second)
  2674.                   (t
  2675.                    (error "can't recognize option `%s'"
  2676.                           (prin1-to-string option))))))
  2677.  
  2678.           (:constructor                 ;no BOA-constructors allowed
  2679.            (setq const
  2680.                  (cond
  2681.                   ((and (symbolp option-second)
  2682.                         (null option-rest))
  2683.                    option-second)
  2684.                   (t
  2685.                    (error "can't recognize option `%s'"
  2686.                           (prin1-to-string option))))))
  2687.           (:predicate
  2688.            (setq pred
  2689.                  (cond
  2690.                   ((and (symbolp option-second)
  2691.                         (null option-rest))
  2692.                    option-second)
  2693.                   (t
  2694.                    (error "can't recognize option `%s'"
  2695.                           (prin1-to-string option))))))
  2696.           (:include
  2697.            (unless (symbolp option-second)
  2698.              (error "arg to `:include' should be a symbol, not `%s'"
  2699.                     (prin1-to-string option-second)))
  2700.            (setq these-slotsn (get option-second :structure-slotsn)
  2701.                  these-slots  (get option-second :structure-slots)
  2702.                  these-inits  (get option-second :structure-initforms))
  2703.            (unless (and (numberp these-slotsn)
  2704.                         (> these-slotsn 0))
  2705.              (error "`%s' is not a valid structure"
  2706.                     (prin1-to-string option-second)))
  2707.            (if included
  2708.                (error "`%s' already includes `%s', can't include `%s' too"
  2709.                       name (car included) option-second)
  2710.              (push option-second included))
  2711.            (multiple-value-bind
  2712.                (xtra-slotsn xtra-slots xtra-inits)
  2713.                (process$slots option-rest)
  2714.              (when (> xtra-slotsn 0)
  2715.                (dolist (xslot xtra-slots)
  2716.                  (unless (memq xslot these-slots)
  2717.                    (error "`%s' is not a slot of `%s'"
  2718.                           (prin1-to-string xslot)
  2719.                           (prin1-to-string option-second))))
  2720.                (setq these-inits (append xtra-inits these-inits)))
  2721.              (setq moreslotsn (+ moreslotsn these-slotsn))
  2722.              (setq moreslots  (append these-slots moreslots))
  2723.              (setq moreinits  (append these-inits moreinits))))
  2724.           ((:print-function :type :initial-offset)
  2725.            )                            ;ignore silently
  2726.           (t
  2727.            (error "can't recognize option `%s'"
  2728.                   (prin1-to-string option)))))
  2729.        (t
  2730.         (error "can't recognize option `%s'"
  2731.                (prin1-to-string option)))))
  2732.     ;; Return values found
  2733.     (values conc-name const copier pred
  2734.             moreslotsn moreslots moreinits
  2735.             included)))
  2736.  
  2737. (defun simplify$inits (slots initlist)
  2738.   "(simplify$inits SLOTS INITLIST) => new INITLIST
  2739. Removes from INITLIST - an ALIST - any shadowed bindings."
  2740.   (let ((result '())                    ;built here
  2741.         key                             ;from the slot 
  2742.         )
  2743.     (dolist (slot slots)
  2744.       (setq key (keyword-of slot))
  2745.       (setq result (acons key (cdr (assoc key initlist)) result)))
  2746.     (nreverse result)))
  2747.  
  2748. (defun extract$indices (initlist)
  2749.   "(extract$indices INITLIST) => indices list
  2750. Kludge.  From a list of pairs (keyword . form) build a list of pairs
  2751. of the form (keyword . position in list from 0).  Useful to precompute
  2752. some of the work of MAKE$STRUCTURE$INSTANCE."
  2753.   (let ((result '())
  2754.         (index   0))
  2755.     (dolist (entry initlist (nreverse result))
  2756.       (setq result (acons (car entry) index result)
  2757.             index  (+ index 1)))))
  2758.  
  2759. (defun build$accessors$for (name conc-name predicate slots slotsn)
  2760.   "(build$accessors$for NAME PREDICATE SLOTS SLOTSN) => FSETS DEFSETFS KWDS
  2761. Generate the code for accesors and defsetfs of a structure called
  2762. NAME, whose slots are SLOTS.  Also, establishes the keywords for the
  2763. slots names."
  2764.   (do ((i 0 (1+ i))
  2765.        (accessors '())
  2766.        (alterators '())
  2767.        (keywords '())
  2768.        (canonic  ""))                   ;slot name with conc-name prepended
  2769.       ((>= i slotsn)
  2770.        (values
  2771.         (nreverse accessors) (nreverse alterators) (nreverse keywords)))
  2772.     (setq canonic (intern (concat conc-name (symbol-name (nth i slots)))))
  2773.     (setq accessors
  2774.           (cons
  2775.            (list 'fset (list 'quote canonic)
  2776.                  (list 'function
  2777.                        (list 'lambda (list 'object)
  2778.                              (list 'cond
  2779.                                    (list (list predicate 'object)
  2780.                                          (list 'aref 'object (1+ i)))
  2781.                                    (list 't
  2782.                                          (list 'error
  2783.                                                "`%s' is not a struct %s"
  2784.                                                (list 'prin1-to-string
  2785.                                                      'object)
  2786.                                                (list 'prin1-to-string
  2787.                                                      (list 'quote
  2788.                                                            name))))))))
  2789.            accessors))
  2790.     (setq alterators
  2791.            (cons
  2792.             (list 'defsetf canonic
  2793.                   (list 'lambda (list 'object 'newval)
  2794.                         (list 'cond
  2795.                               (list (list predicate 'object)
  2796.                                     (list 'aset 'object (1+ i) 'newval))
  2797.                               (list 't
  2798.                                     (list 'error
  2799.                                           "`%s' not a `%s'"
  2800.                                           (list 'prin1-to-string
  2801.                                                 'object)
  2802.                                           (list 'prin1-to-string
  2803.                                                 (list 'quote
  2804.                                                       name)))))))
  2805.             alterators))
  2806.     (setq keywords
  2807.           (cons (list 'defkeyword (keyword-of (nth i slots)))
  2808.                 keywords))))
  2809.  
  2810. (defun make$structure$instance (name args)
  2811.   "(make$structure$instance NAME ARGS) => new struct NAME
  2812. A struct of type NAME is created, some slots might be initialized
  2813. according to ARGS (the &rest argument of MAKE-name)."
  2814.   (unless (symbolp name)
  2815.     (error "`%s' is not a possible name for a structure"
  2816.            (prin1-to-string name)))
  2817.   (let ((initforms (get name :structure-initforms))
  2818.         (slotsn    (get name :structure-slotsn))
  2819.         (indices   (get name :structure-indices))
  2820.         initalist                       ;pairlis'd on initforms
  2821.         initializers                    ;definitive initializers
  2822.         )
  2823.     ;; check sanity of the request
  2824.     (unless (and (numberp slotsn)
  2825.                  (> slotsn 0))
  2826.       (error "`%s' is not a defined structure"
  2827.              (prin1-to-string name)))
  2828.     (unless (evenp (length args))
  2829.       (error "slot initializers `%s' not of even length"
  2830.              (prin1-to-string args)))
  2831.     ;; analyze the initializers provided by the call
  2832.     (multiple-value-bind
  2833.         (speckwds specvals)             ;keywords and values given 
  2834.         (unzip-list args)               ; by the user
  2835.       ;; check that all the arguments are introduced by keywords 
  2836.       (unless (every (function keywordp) speckwds)
  2837.         (error "all of the names in `%s' should be keywords"
  2838.                (prin1-to-string speckwds)))
  2839.       ;; check that all the keywords are known
  2840.       (dolist (kwd speckwds)
  2841.         (unless (numberp (cdr (assoc kwd indices)))
  2842.           (error "`%s' is not a valid slot name for %s"
  2843.                  (prin1-to-string kwd) (prin1-to-string name))))
  2844.       ;; update initforms
  2845.       (setq initalist
  2846.             (pairlis speckwds
  2847.                      (do* ;;protect values from further evaluation
  2848.                          ((ptr specvals (cdr ptr))
  2849.                           (val (car ptr) (car ptr))
  2850.                           (result '()))
  2851.                          ((endp ptr) (nreverse result))
  2852.                        (setq result
  2853.                              (cons (list 'quote val)
  2854.                                    result)))
  2855.                      (copy-sequence initforms)))
  2856.       ;; compute definitive initializers
  2857.       (setq initializers
  2858.             (do* ;;gather the values of the most definitive forms
  2859.                 ((ptr indices (cdr ptr))
  2860.                  (key (caar ptr) (caar ptr))
  2861.                  (result '()))
  2862.                 ((endp ptr) (nreverse result))
  2863.               (setq result
  2864.                     (cons (eval (cdr (assoc key initalist))) result))))
  2865.       ;; do real initialization
  2866.       (apply (function vector)
  2867.              (cons name initializers)))))
  2868.  
  2869. ;;;; end of cl-structs.el
  2870.  
  2871. ;;; For lisp-interaction mode, so that multiple values can be seen when passed
  2872. ;;; back.  Lies every now and then...
  2873.  
  2874. (defvar - nil "form currently under evaluation")
  2875. (defvar + nil "previous -")
  2876. (defvar ++ nil "previous +")
  2877. (defvar +++ nil "previous ++")
  2878. (defvar / nil "list of values returned by +")
  2879. (defvar // nil "list of values returned by ++")
  2880. (defvar /// nil "list of values returned by +++")
  2881. (defvar * nil "(first) value of +")
  2882. (defvar ** nil "(first) value of ++")
  2883. (defvar *** nil "(first) value of +++")
  2884.  
  2885. (defun cl-eval-print-last-sexp ()
  2886.   "Evaluate sexp before point; print value\(s\) into current buffer.
  2887. If the evaled form returns multiple values, they are shown one to a line.
  2888. The variables -, +, ++, +++, *, **, ***, /, //, /// have their usual meaning.
  2889.  
  2890. It clears the multiple-value passing mechanism, and does not pass back
  2891. multiple values.  Use this only if you are debugging cl.el and understand well
  2892. how the multiple-value stuff works, because it can be fooled into believing
  2893. that multiple values have been returned when they actually haven't, for
  2894. instance 
  2895.     \(identity \(values nil 1\)\)
  2896. However, even when this fails, you can trust the first printed value to be
  2897. \(one of\) the returned value\(s\)."
  2898.   (interactive)
  2899.   ;; top level call, can reset mvalues
  2900.   (setq *mvalues-count*  nil
  2901.         *mvalues-values* nil)
  2902.   (setq -  (car (read-from-string
  2903.                  (buffer-substring
  2904.                   (let ((stab (syntax-table)))
  2905.                     (unwind-protect
  2906.                         (save-excursion
  2907.                           (set-syntax-table emacs-lisp-mode-syntax-table)
  2908.                           (forward-sexp -1)
  2909.                           (point))
  2910.                       (set-syntax-table stab)))
  2911.                   (point)))))
  2912.   (setq *** **
  2913.         **  *
  2914.         *   (eval -))
  2915.   (setq /// //
  2916.         //  /
  2917.         /   *mvalues-values*)
  2918.   (setq +++ ++
  2919.         ++  +
  2920.         +   -)
  2921.   (cond ((or (null *mvalues-count*)     ;mvalues mechanism not used
  2922.              (not (eq * (car *mvalues-values*))))
  2923.          (print * (current-buffer)))
  2924.         ((null /)                       ;no values returned
  2925.          (terpri (current-buffer)))
  2926.         (t                              ;more than zero mvalues
  2927.          (terpri (current-buffer))
  2928.          (mapcar (function (lambda (value)
  2929.                              (prin1 value (current-buffer))
  2930.                              (terpri (current-buffer))))
  2931.                  /)))
  2932.   (setq *mvalues-count*  nil            ;make sure
  2933.         *mvalues-values* nil))
  2934.  
  2935. ;;;; More LISTS functions
  2936. ;;;;
  2937.  
  2938. ;;; Some mapping functions on lists, commonly useful.
  2939. ;;; They take no extra sequences, to go along with Emacs Lisp's MAPCAR.
  2940.  
  2941. (defun mapc (function list)
  2942.   "(MAPC FUNCTION LIST) => LIST
  2943. Apply FUNCTION to each element of LIST, return LIST.
  2944. Like mapcar, but called only for effect."
  2945.   (let ((args list))
  2946.     (while args
  2947.       (funcall function (car args))
  2948.       (setq args (cdr args))))
  2949.   list)
  2950.  
  2951. (defun maplist (function list)
  2952.   "(MAPLIST FUNCTION LIST) => list'ed results of FUNCTION on cdrs of LIST
  2953. Apply FUNCTION to successive sublists of LIST, return the list of the results"
  2954.   (let ((args list)
  2955.         results '())
  2956.     (while args
  2957.       (setq results (cons (funcall function args) results)
  2958.             args (cdr args)))
  2959.     (nreverse results)))
  2960.  
  2961. (defun mapl (function list)
  2962.   "(MAPL FUNCTION LIST) => LIST
  2963. Apply FUNCTION to successive cdrs of LIST, return LIST.
  2964. Like maplist, but called only for effect."
  2965.   (let ((args list))
  2966.     (while args
  2967.       (funcall function args)
  2968.       (setq args (cdr args)))
  2969.     list))
  2970.  
  2971. (defun mapcan (function list)
  2972.   "(MAPCAN FUNCTION LIST) => nconc'd results of FUNCTION on LIST
  2973. Apply FUNCTION to each element of LIST, nconc the results.
  2974. Beware: nconc destroys its first argument!  See copy-list."
  2975.   (let ((args list)
  2976.         (results '()))
  2977.     (while args
  2978.       (setq results (nconc (funcall function (car args)) results)
  2979.             args (cdr args)))
  2980.     (nreverse results)))
  2981.  
  2982. (defun mapcon (function list)
  2983.   "(MAPCON FUNCTION LIST) => nconc'd results of FUNCTION on cdrs of LIST
  2984. Apply FUNCTION to successive sublists of LIST, nconc the results.
  2985. Beware: nconc destroys its first argument!  See copy-list."
  2986.   (let ((args list)
  2987.         (results '()))
  2988.     (while args
  2989.       (setq results (nconc (funcall function args) results)
  2990.             args (cdr args)))
  2991.     (nreverse results)))
  2992.  
  2993. ;;; Copiers
  2994.  
  2995. (defsubst copy-list (list)
  2996.   "Build a copy of LIST"
  2997.   (append list '()))
  2998.  
  2999. (defun copy-tree (tree)
  3000.   "Build a copy of the tree of conses TREE
  3001. The argument is a tree of conses, it is recursively copied down to
  3002. non conses.  Circularity and sharing of substructure are not
  3003. necessarily preserved."
  3004.   (if (consp tree)
  3005.       (cons (copy-tree (car tree))
  3006.             (copy-tree (cdr tree)))
  3007.     tree))
  3008.  
  3009. ;;; reversals, and destructive manipulations of a list's spine
  3010.  
  3011. (defun revappend (x y)
  3012.   "does what (append (reverse X) Y) would, only faster"
  3013.   (if (endp x)
  3014.       y
  3015.     (revappend (cdr x) (cons (car x) y))))
  3016.  
  3017. (defun nreconc (x y)
  3018.   "does (nconc (nreverse X) Y) would, only faster
  3019. Destructive on X, be careful."
  3020.   (if (endp x)
  3021.       y
  3022.     ;; reuse the first cons of x, making it point to y
  3023.     (nreconc (cdr x) (prog1 x (rplacd x y)))))
  3024.  
  3025. (defun nbutlast (list &optional n)
  3026.   "Side-effected LIST truncated N+1 conses from the end.
  3027. This is the destructive version of BUTLAST.  Returns () and does not
  3028. modify the LIST argument if the length of the list is not at least N."
  3029.   (when (null n) (setf n 1))
  3030.   (let ((length (list-length list)))
  3031.     (cond ((null length)
  3032.            list)
  3033.           ((< length n)
  3034.            '())
  3035.           (t
  3036.            (setnthcdr (- length n) list nil)
  3037.            list))))
  3038.  
  3039. ;;; Substitutions
  3040.  
  3041. (defun subst (new old tree)
  3042.   "NEW replaces OLD in a copy of TREE
  3043. Uses eql for the test."
  3044.   (subst-if new (function (lambda (x) (eql x old))) tree))
  3045.  
  3046. (defun subst-if-not (new test tree)
  3047.   "NEW replaces any subtree or leaf that fails TEST in a copy of TREE"
  3048.   ;; (subst-if new (function (lambda (x) (not (funcall test x)))) tree)
  3049.   (cond ((not (funcall test tree))
  3050.          new)
  3051.         ((atom tree)
  3052.          tree)
  3053.         (t                              ;no match so far
  3054.          (let ((head (subst-if-not new test (car tree)))
  3055.                (tail (subst-if-not new test (cdr tree))))
  3056.            ;; If nothing changed, return originals.  Else use the new
  3057.            ;; components to assemble a new tree.
  3058.            (if (and (eql head (car tree))
  3059.                     (eql tail (cdr tree)))
  3060.                tree
  3061.              (cons head tail))))))
  3062.  
  3063. (defun subst-if (new test tree)
  3064.   "NEW replaces any subtree or leaf that satisfies TEST in a copy of TREE"
  3065.   (cond ((funcall test tree)
  3066.          new)
  3067.         ((atom tree)
  3068.          tree)
  3069.         (t                              ;no match so far
  3070.          (let ((head (subst-if new test (car tree)))
  3071.                (tail (subst-if new test (cdr tree))))
  3072.            ;; If nothing changed, return originals.  Else use the new
  3073.            ;; components to assemble a new tree.
  3074.            (if (and (eql head (car tree))
  3075.                     (eql tail (cdr tree)))
  3076.                tree
  3077.              (cons head tail))))))
  3078.  
  3079. (defun sublis (alist tree)
  3080.   "Use association list ALIST to modify a copy of TREE
  3081. If a subtree or leaf of TREE is a key in ALIST, it is replaced by the
  3082. associated value.  Not exactly Common Lisp, but close in spirit and
  3083. compatible with the native Emacs Lisp ASSOC, which uses EQUAL."
  3084.   (let ((toplevel (assoc tree alist)))
  3085.     (cond (toplevel                     ;Bingo at top
  3086.            (cdr toplevel))
  3087.           ((atom tree)                  ;Give up on this
  3088.            tree)
  3089.           (t
  3090.            (let ((head (sublis alist (car tree)))
  3091.                  (tail (sublis alist (cdr tree))))
  3092.              (if (and (eql head (car tree))
  3093.                       (eql tail (cdr tree)))
  3094.                  tree
  3095.                (cons head tail)))))))
  3096.  
  3097. (defun member-if (predicate list)
  3098.   "PREDICATE is applied to the members of LIST.  As soon as one of them
  3099. returns true, that tail of the list if returned.  Else NIL."
  3100.   (catch 'found-member-if
  3101.     (while (not (endp list))
  3102.       (if (funcall predicate (car list))
  3103.           (throw 'found-member-if list)
  3104.         (setq list (cdr list))))
  3105.     nil))
  3106.  
  3107. (defun member-if-not (predicate list)
  3108.   "PREDICATE is applied to the members of LIST.  As soon as one of them
  3109. returns false, that tail of the list if returned.  Else NIL."
  3110.   (catch 'found-member-if-not
  3111.     (while (not (endp list))
  3112.       (if (funcall predicate (car list))
  3113.           (setq list (cdr list))
  3114.         (throw 'found-member-if-not list)))
  3115.     nil))
  3116.  
  3117. (defun tailp (sublist list)
  3118.   "(tailp SUBLIST LIST) => True if SUBLIST is a sublist of LIST."
  3119.   (catch 'tailp-found
  3120.     (while (not (endp list))
  3121.       (if (eq sublist list)
  3122.           (throw 'tailp-found t)
  3123.         (setq list (cdr list))))
  3124.     nil))
  3125.  
  3126. ;;; Suggestion of phr%widow.Berkeley.EDU@lilac.berkeley.edu
  3127.  
  3128. (defmacro declare (&rest decls)
  3129.   "Ignore a Common-Lisp declaration."
  3130.   "declarations are ignored in this implementation")
  3131.  
  3132. (defun proclaim (&rest decls)
  3133.   "Ignore a Common-Lisp proclamation."
  3134.   "declarations are ignored in this implementation")
  3135.  
  3136. (defmacro the (type form)
  3137.   "(the TYPE FORM) macroexpands to FORM
  3138. No checking is even attempted.  This is just for compatibility with
  3139. Common-Lisp codes."
  3140.   form)
  3141.  
  3142. ;;; Due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
  3143. (put 'progv 'common-lisp-indent-hook '(4 4 &body))
  3144. (defmacro progv (vars vals &rest body)
  3145.   "progv vars vals &body forms
  3146. bind vars to vals then execute forms.
  3147. If there are more vars than vals, the extra vars are unbound, if
  3148. there are more vals than vars, the extra vals are just ignored."
  3149.   (` (progv$runtime (, vars) (, vals) (function (lambda () (,@ body))))))
  3150.  
  3151. ;;; To do this efficiently, it really needs to be a special form...
  3152. (defun progv$runtime (vars vals body)
  3153.   (eval (let ((vars-n-vals nil)
  3154.           (unbind-forms nil))
  3155.       (do ((r vars (cdr r))
  3156.            (l vals (cdr l)))
  3157.           ((endp r))
  3158.         (push (list (car r) (list 'quote (car l))) vars-n-vals)
  3159.         (if (null l)
  3160.         (push (` (makunbound '(, (car r)))) unbind-forms)))
  3161.       (` (let (, vars-n-vals) (,@ unbind-forms) (funcall '(, body)))))))
  3162.  
  3163. (provide 'cl)
  3164.  
  3165. ;;;; end of cl.el
  3166.