1 ;;; cl.el --- Common-Lisp extensions for GNU Emacs Lisp.
3 ;; Author: Cesar Quiroz <quiroz@cs.rochester.edu>
4 ;; Last-Modified: 16 Mar 1992
5 ;; Keywords: extensions
7 (defvar cl-version
"2.0 beta 29 October 1989")
9 ;; Copyright (C) 1987, 1988, 1989 Free Software Foundation, Inc.
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY. No author or distributor
15 ;; accepts responsibility to anyone for the consequences of using it
16 ;; or for whether it serves any particular purpose or works at all,
17 ;; unless he says so in writing. Refer to the GNU Emacs General Public
18 ;; License for full details.
20 ;; Everyone is granted permission to copy, modify and redistribute
21 ;; GNU Emacs, but only under the conditions described in the
22 ;; GNU Emacs General Public License. A copy of this license is
23 ;; supposed to have been given to you along with GNU Emacs so you
24 ;; can know your rights and responsibilities. It should be in a
25 ;; file named COPYING. Among other things, the copyright notice
26 ;; and this notice must be preserved on all copies.
30 ;;;; These are extensions to Emacs Lisp that provide some form of
31 ;;;; Common Lisp compatibility, beyond what is already built-in
34 ;;;; When developing them, I had the code spread among several files.
35 ;;;; This file 'cl.el' is a concatenation of those original files,
36 ;;;; minus some declarations that became redundant. The marks between
37 ;;;; the original files can be found easily, as they are lines that
38 ;;;; begin with four semicolons (as this does). The names of the
39 ;;;; original parts follow the four semicolons in uppercase, those
40 ;;;; names are GLOBAL, SYMBOLS, LISTS, SEQUENCES, CONDITIONALS,
41 ;;;; ITERATIONS, MULTIPLE VALUES, ARITH, SETF and DEFSTRUCT. If you
42 ;;;; add functions to this file, you might want to put them in a place
43 ;;;; that is compatible with the division above (or invent your own
46 ;;;; To compile this file, make sure you load it first. This is
47 ;;;; because many things are implemented as macros and now that all
48 ;;;; the files are concatenated together one cannot ensure that
49 ;;;; declaration always precedes use.
53 ;;;; This file provides utilities and declarations that are global
54 ;;;; to Common Lisp and so might be used by more than one of the
55 ;;;; other libraries. Especially, I intend to keep here some
56 ;;;; utilities that help parsing/destructuring some difficult calls.
59 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
60 ;;;; (quiroz@cs.rochester.edu)
62 ;;; Too many pieces of the rest of this package use psetq. So it is unwise to
63 ;;; use here anything but plain Emacs Lisp! There is a neater recursive form
64 ;;; for the algorithm that deals with the bodies.
68 (defmacro psetq
(&rest body
)
69 "(psetq {var value }...) => nil
70 Like setq, but all the values are computed before any assignment is made."
71 (let ((length (length body
)))
72 (cond ((/= (% length
2) 0)
73 (error "psetq needs an even number of arguments, %d given"
80 (bodyforms (reverse body
)))
82 (let* ((value (car bodyforms
))
83 (place (cadr bodyforms
)))
84 (setq bodyforms
(cddr bodyforms
))
86 (setq setqs
(list 'setq place value
))
87 (setq setqs
(list 'setq place
94 ;;; pair-with-newsyms takes a list and returns a list of lists of the
95 ;;; form (newsym form), such that a let* can then bind the evaluation
96 ;;; of the forms to the newsyms. The idea is to guarantee correct
97 ;;; order of evaluation of the subforms of a setf. It also returns a
98 ;;; list of the newsyms generated, in the corresponding order.
100 (defun pair-with-newsyms (oldforms)
101 "PAIR-WITH-NEWSYMS OLDFORMS
102 The top-level components of the list oldforms are paired with fresh
103 symbols, the pairings list and the newsyms list are returned."
104 (do ((ptr oldforms
(cdr ptr
))
107 ((endp ptr
) (values (nreverse bindings
) (nreverse newsyms
)))
108 (let ((newsym (gentemp)))
109 (setq bindings
(cons (list newsym
(car ptr
)) bindings
))
110 (setq newsyms
(cons newsym newsyms
)))))
112 (defun zip-lists (evens odds
)
113 "Merge two lists EVENS and ODDS, taking elts from each list alternatingly.
114 EVENS and ODDS are two lists. ZIP-LISTS constructs a new list, whose
115 even numbered elements (0,2,...) come from EVENS and whose odd numbered
116 elements (1,3,...) come from ODDS.
117 The construction stops when the shorter list is exhausted."
118 (do* ((p0 evens
(cdr p0
))
120 (even (car p0
) (car p0
))
121 (odd (car p1
) (car p1
))
123 ((or (endp p0
) (endp p1
))
126 (cons odd
(cons even result
)))))
128 (defun unzip-list (list)
129 "Extract even and odd elements of LIST into two separate lists.
130 The argument LIST is separated in two strands, the even and the odd
131 numbered elements. Numbering starts with 0, so the first element
132 belongs in EVENS. No check is made that there is an even number of
133 elements to start with."
134 (do* ((ptr list
(cddr ptr
))
135 (this (car ptr
) (car ptr
))
136 (next (cadr ptr
) (cadr ptr
))
140 (values (nreverse evens
) (nreverse odds
)))
141 (setq evens
(cons this evens
))
142 (setq odds
(cons next odds
))))
144 (defun reassemble-argslists (argslists)
145 "(reassemble-argslists ARGSLISTS) => a list of lists
146 ARGSLISTS is a list of sequences. Return a list of lists, the first
147 sublist being all the entries coming from ELT 0 of the original
148 sublists, the next those coming from ELT 1 and so on, until the
149 shortest list is exhausted."
150 (let* ((minlen (apply 'min
(mapcar 'length argslists
)))
152 (dotimes (i minlen
(nreverse result
))
153 ;; capture all the elements at index i
155 (cons (mapcar (function (lambda (sublist) (elt sublist i
)))
160 ;;; Checking that a list of symbols contains no duplicates is a common
161 ;;; task when checking the legality of some macros. The check for 'eq
162 ;;; pairs can be too expensive, as it is quadratic on the length of
163 ;;; the list. I use a 4-pass, linear, counting approach. It surely
164 ;;; loses on small lists (less than 5 elements?), but should win for
165 ;;; larger lists. The fourth pass could be eliminated.
166 ;;; 10 dec 1986. Emacs Lisp has no REMPROP, so I just eliminated the
168 (defun duplicate-symbols-p (list)
169 "Find all symbols appearing more than once in LIST.
170 Return a list of all such duplicates; nil if there are no duplicates."
171 (let ((duplicates '()) ;result built here
172 (propname (gensym)) ;we use a fresh property
175 (unless (and (listp list
)
176 (every 'symbolp list
))
177 (error "a list of symbols is needed"))
183 (put x propname
(1+ (get x propname
))))
186 (if (> (get x propname
) 1)
187 (setq duplicates
(cons x duplicates
))))
188 ;; pass 4: unmark. eliminated.
189 ;; (dolist (x list) (remprop x propname))
193 ;;;; end of cl-global.el
196 ;;;; This file provides the gentemp function, which generates fresh
197 ;;;; symbols, plus some other minor Common Lisp symbol tools.
199 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
200 ;;;; (quiroz@cs.rochester.edu)
202 ;;; Keywords. There are no packages in Emacs Lisp, so this is only a
203 ;;; kludge around to let things be "as if" a keyword package was around.
205 (defmacro defkeyword
(x &optional docstring
)
206 "Make symbol X a keyword (symbol whose value is itself).
207 Optional second arg DOCSTRING is a documentation string for it."
209 (list 'defconst x
(list 'quote x
) docstring
))
211 (error "`%s' is not a symbol" (prin1-to-string x
)))))
213 (defun keywordp (sym)
214 "Return t if SYM is a keyword."
215 (if (and (symbolp sym
) (char-equal (aref (symbol-name sym
) 0) ?\
:))
216 ;; looks like one, make sure value is right
220 (defun keyword-of (sym)
221 "Return a keyword that is naturally associated with symbol SYM.
222 If SYM is keyword, the value is SYM.
223 Otherwise it is a keyword whose name is `:' followed by SYM's name."
224 (cond ((keywordp sym
)
227 (let ((newsym (intern (concat ":" (symbol-name sym
)))))
228 (set newsym newsym
)))
230 (error "expected a symbol, not `%s'" (prin1-to-string sym
)))))
232 ;;; Temporary symbols.
235 (defvar *gentemp-index
* 0
236 "Integer used by `gentemp' to produce new names.")
238 (defvar *gentemp-prefix
* "T$$_"
239 "Names generated by `gentemp begin' with this string by default.")
241 (defun gentemp (&optional prefix oblist
)
242 "Generate a fresh interned symbol.
243 There are two optional arguments, PREFIX and OBLIST. PREFIX is the string
244 that begins the new name, OBLIST is the obarray used to search for old
245 names. The defaults are just right, YOU SHOULD NEVER NEED THESE ARGUMENTS
248 (setq prefix
*gentemp-prefix
*))
250 (setq oblist obarray
)) ;default for the intern functions
251 (let ((newsymbol nil
)
253 (while (not newsymbol
)
254 (setq newname
(concat prefix
*gentemp-index
*))
255 (setq *gentemp-index
* (+ *gentemp-index
* 1))
256 (if (not (intern-soft newname oblist
))
257 (setq newsymbol
(intern newname oblist
))))
260 (defvar *gensym-index
* 0
261 "Integer used by `gensym' to produce new names.")
263 (defvar *gensym-prefix
* "G$$_"
264 "Names generated by `gensym' begin with this string by default.")
266 (defun gensym (&optional prefix
)
267 "Generate a fresh uninterned symbol.
268 Optional arg PREFIX is the string that begins the new name. Most people
269 take just the default, except when debugging needs suggest otherwise."
271 (setq prefix
*gensym-prefix
*))
272 (let ((newsymbol nil
)
274 (while (not newsymbol
)
275 (setq newname
(concat prefix
*gensym-index
*))
276 (setq *gensym-index
* (+ *gensym-index
* 1))
277 (if (not (intern-soft newname
))
278 (setq newsymbol
(make-symbol newname
))))
281 ;;;; end of cl-symbols.el
284 ;;;; This file provides some of the conditional constructs of
285 ;;;; Common Lisp. Total compatibility is again impossible, as the
286 ;;;; 'if' form is different in both languages, so only a good
287 ;;;; approximation is desired.
289 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
290 ;;;; (quiroz@cs.rochester.edu)
293 (put 'case
'lisp-indent-function
1)
294 (put 'ecase
'lisp-indent-function
1)
295 (put 'when
'lisp-indent-function
1)
296 (put 'unless
'lisp-indent-function
1)
299 ;;; These two forms are simplified ifs, with a single branch.
301 (defmacro when
(condition &rest body
)
302 "(when CONDITION . BODY) => evaluate BODY if CONDITION is true."
303 (list* 'if
(list 'not condition
) '() body
))
305 (defmacro unless
(condition &rest body
)
306 "(unless CONDITION . BODY) => evaluate BODY if CONDITION is false."
307 (list* 'if condition
'() body
))
310 ;;; CASE selects among several clauses, based on the value (evaluated)
311 ;;; of a expression and a list of (unevaluated) key values. ECASE is
312 ;;; the same, but signals an error if no clause is activated.
314 (defmacro case
(expr &rest cases
)
315 "(case EXPR . CASES) => evals EXPR, chooses from CASES on that value.
317 CASES -> list of clauses, non empty
318 CLAUSE -> HEAD . BODY
319 HEAD -> t = catch all, must be last clause
320 -> otherwise = same as t
322 -> atom = activated if (eql EXPR HEAD)
323 -> list of atoms = activated if (memq EXPR HEAD)
324 BODY -> list of forms, implicit PROGN is built around it.
325 EXPR is evaluated only once."
326 (let* ((newsym (gentemp))
327 (clauses (case-clausify cases newsym
)))
328 ;; convert case into a cond inside a let
330 (list (list newsym expr
))
331 (list* 'cond
(nreverse clauses
)))))
333 (defmacro ecase
(expr &rest cases
)
334 "(ecase EXPR . CASES) => like `case', but error if no case fits.
335 `t'-clauses are not allowed."
336 (let* ((newsym (gentemp))
337 (clauses (case-clausify cases newsym
)))
338 ;; check that no 't clause is present.
339 ;; case-clausify would put one such at the beginning of clauses
340 (if (eq (caar clauses
) t
)
341 (error "no clause-head should be `t' or `otherwise' for `ecase'"))
342 ;; insert error-catching clause
345 (list 't
(list 'error
346 "ecase on %s = %s failed to take any branch"
348 (list 'prin1-to-string newsym
)))
350 ;; generate code as usual
352 (list (list newsym expr
))
353 (list* 'cond
(nreverse clauses
)))))
356 (defun case-clausify (cases newsym
)
357 "CASE-CLAUSIFY CASES NEWSYM => clauses for a 'cond'
358 Converts the CASES of a [e]case macro into cond clauses to be
359 evaluated inside a let that binds NEWSYM. Returns the clauses in
361 (do* ((currentpos cases
(cdr currentpos
))
362 (nextpos (cdr cases
) (cdr nextpos
))
363 (curclause (car cases
) (car currentpos
))
365 ((endp currentpos
) result
)
366 (let ((head (car curclause
))
367 (body (cdr curclause
)))
368 ;; construct a cond-clause according to the head
370 (error "case clauses cannot have null heads: `%s'"
371 (prin1-to-string curclause
)))
373 (eq head
'otherwise
))
374 ;; check it is the last clause
375 (if (not (endp nextpos
))
376 (error "clause with `t' or `otherwise' head must be last"))
377 ;; accept this clause as a 't' for cond
378 (setq result
(cons (cons 't body
) result
)))
381 (cons (cons (list 'eql newsym
(list 'quote head
)) body
)
385 (cons (cons (list 'memq newsym
(list 'quote head
)) body
)
388 ;; catch-all for this parser
389 (error "don't know how to parse case clause `%s'"
390 (prin1-to-string head
)))))))
392 ;;;; end of cl-conditionals.el
395 ;;;; This file provides simple iterative macros (a la Common Lisp)
396 ;;;; constructed on the basis of let, let* and while, which are the
397 ;;;; primitive binding/iteration constructs of Emacs Lisp
399 ;;;; The Common Lisp iterations use to have a block named nil
400 ;;;; wrapped around them, and allow declarations at the beginning
401 ;;;; of their bodies and you can return a value using (return ...).
402 ;;;; Nothing of the sort exists in Emacs Lisp, so I haven't tried
403 ;;;; to imitate these behaviors.
405 ;;;; Other than the above, the semantics of Common Lisp are
406 ;;;; correctly reproduced to the extent this was reasonable.
408 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
409 ;;;; (quiroz@cs.rochester.edu)
411 ;;; some lisp-indentation information
412 (put 'do
'lisp-indent-function
2)
413 (put 'do
* 'lisp-indent-function
2)
414 (put 'dolist
'lisp-indent-function
1)
415 (put 'dotimes
'lisp-indent-function
1)
416 (put 'do-symbols
'lisp-indent-function
1)
417 (put 'do-all-symbols
'lisp-indent-function
1)
420 (defmacro do
(stepforms endforms
&rest body
)
421 "(do STEPFORMS ENDFORMS . BODY): Iterate BODY, stepping some local
422 variables. STEPFORMS must be a list of symbols or lists. In the second
423 case, the lists must start with a symbol and contain up to two more forms.
424 In the STEPFORMS, a symbol is the same as a (symbol). The other two forms
425 are the initial value (def. NIL) and the form to step (def. itself).
427 The values used by initialization and stepping are computed in parallel.
428 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION evaluates
429 to true in any iteration, ENDBODY is evaluated and the last form in it is
432 The BODY (which may be empty) is evaluated at every iteration, with the
433 symbols of the STEPFORMS bound to the initial or stepped values."
435 ;; check the syntax of the macro
436 (and (check-do-stepforms stepforms
)
437 (check-do-endforms endforms
))
438 ;; construct emacs-lisp equivalent
439 (let ((initlist (extract-do-inits stepforms
))
440 (steplist (extract-do-steps stepforms
))
441 (endcond (car endforms
))
442 (endbody (cdr endforms
)))
443 (cons 'let
(cons initlist
444 (cons (cons 'while
(cons (list 'not endcond
)
445 (append body steplist
)))
446 (append endbody
))))))
449 (defmacro do
* (stepforms endforms
&rest body
)
450 "`do*' is to `do' as `let*' is to `let'.
451 STEPFORMS must be a list of symbols or lists. In the second case, the
452 lists must start with a symbol and contain up to two more forms. In the
453 STEPFORMS, a symbol is the same as a (symbol). The other two forms are
454 the initial value (def. NIL) and the form to step (def. itself).
456 Initializations and steppings are done in the sequence they are written.
458 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION evaluates
459 to true in any iteration, ENDBODY is evaluated and the last form in it is
462 The BODY (which may be empty) is evaluated at every iteration, with
463 the symbols of the STEPFORMS bound to the initial or stepped values."
464 ;; check the syntax of the macro
465 (and (check-do-stepforms stepforms
)
466 (check-do-endforms endforms
))
467 ;; construct emacs-lisp equivalent
468 (let ((initlist (extract-do-inits stepforms
))
469 (steplist (extract-do*-steps stepforms
))
470 (endcond (car endforms
))
471 (endbody (cdr endforms
)))
472 (cons 'let
* (cons initlist
473 (cons (cons 'while
(cons (list 'not endcond
)
474 (append body steplist
)))
475 (append endbody
))))))
478 ;;; DO and DO* share the syntax checking functions that follow.
480 (defun check-do-stepforms (forms)
481 "True if FORMS is a valid stepforms for the do[*] macro (q.v.)"
483 (error "init/step form for do[*] should be a list, not `%s'"
484 (prin1-to-string forms
))
488 (if (not (or (symbolp entry
)
490 (symbolp (car entry
))
491 (< (length entry
) 4))))
492 (error "init/step must be %s, not `%s'"
493 "symbol or (symbol [init [step]])"
494 (prin1-to-string entry
)))))
497 (defun check-do-endforms (forms)
498 "True if FORMS is a valid endforms for the do[*] macro (q.v.)"
500 (error "termination form for do macro should be a list, not `%s'"
501 (prin1-to-string forms
))))
503 (defun extract-do-inits (forms)
504 "Returns a list of the initializations (for do) in FORMS
505 (a stepforms, see the do macro).
506 FORMS is assumed syntactically valid."
510 (cond ((symbolp entry
)
513 (list (car entry
) (cadr entry
))))))
516 ;;; There used to be a reason to deal with DO differently than with
517 ;;; DO*. The writing of PSETQ has made it largely unnecessary.
519 (defun extract-do-steps (forms)
520 "EXTRACT-DO-STEPS FORMS => an s-expr.
521 FORMS is the stepforms part of a DO macro (q.v.). This function constructs
522 an s-expression that does the stepping at the end of an iteration."
523 (list (cons 'psetq
(select-stepping-forms forms
))))
525 (defun extract-do*-steps
(forms)
526 "EXTRACT-DO*-STEPS FORMS => an s-expr.
527 FORMS is the stepforms part of a DO* macro (q.v.). This function constructs
528 an s-expression that does the stepping at the end of an iteration."
529 (list (cons 'setq
(select-stepping-forms forms
))))
531 (defun select-stepping-forms (forms)
532 "Separate only the forms that cause stepping."
533 (let ((result '()) ;ends up being (... var form ...)
534 (ptr forms
) ;to traverse the forms
535 entry
;to explore each form in turn
537 (while ptr
;(not (endp entry)) might be safer
538 (setq entry
(car ptr
))
539 (cond ((and (listp entry
) (= (length entry
) 3))
540 (setq result
(append ;append in reverse order!
541 (list (caddr entry
) (car entry
))
543 (setq ptr
(cdr ptr
))) ;step in the list of forms
546 ;;; Other iterative constructs
548 (defmacro dolist
(stepform &rest body
)
549 "(dolist (VAR LIST [RESULTFORM]) . BODY): do BODY for each elt of LIST.
550 The RESULTFORM defaults to nil. The VAR is bound to successive elements
551 of the value of LIST and remains bound (to the nil value) when the
552 RESULTFORM is evaluated."
556 (error "stepform for `dolist' should be (VAR LIST [RESULT]), not `%s'"
557 (prin1-to-string stepform
)))
558 ((not (symbolp (car stepform
)))
559 (error "first component of stepform should be a symbol, not `%s'"
560 (prin1-to-string (car stepform
))))
561 ((> (length stepform
) 3)
562 (error "too many components in stepform `%s'"
563 (prin1-to-string stepform
))))
565 (let* ((var (car stepform
))
566 (listform (cadr stepform
))
567 (resultform (caddr stepform
)))
571 (cons 'lambda
(cons (list var
) body
)))
574 (list (list var nil
))
577 (defmacro dotimes
(stepform &rest body
)
578 "(dotimes (VAR COUNTFORM [RESULTFORM]) . BODY): Repeat BODY, counting in VAR.
579 The COUNTFORM should return a positive integer. The VAR is bound to
580 successive integers from 0 to COUNTFORM - 1 and the BODY is repeated for
581 each of them. At the end, the RESULTFORM is evaluated and its value
582 returned. During this last evaluation, the VAR is still bound, and its
583 value is the number of times the iteration occurred. An omitted RESULTFORM
588 (error "stepform for `dotimes' should be (VAR COUNT [RESULT]), not `%s'"
589 (prin1-to-string stepform
)))
590 ((not (symbolp (car stepform
)))
591 (error "first component of stepform should be a symbol, not `%s'"
592 (prin1-to-string (car stepform
))))
593 ((> (length stepform
) 3)
594 (error "too many components in stepform `%s'"
595 (prin1-to-string stepform
))))
597 (let* ((var (car stepform
))
598 (countform (cadr stepform
))
599 (resultform (caddr stepform
))
602 'let
* (list (list newsym countform
))
605 (list (list var
0 (list '+ var
1)))
606 (list (list '>= var newsym
) resultform
)
609 (defmacro do-symbols
(stepform &rest body
)
610 "(do_symbols (VAR [OBARRAY [RESULTFORM]]) . BODY)
611 The VAR is bound to each of the symbols in OBARRAY (def. obarray) and
612 the BODY is repeatedly performed for each of those bindings. At the
613 end, RESULTFORM (def. nil) is evaluated and its value returned.
614 During this last evaluation, the VAR is still bound and its value is nil.
615 See also the function `mapatoms'."
619 (error "stepform for `do-symbols' should be (VAR OBARRAY [RESULT]), not `%s'"
620 (prin1-to-string stepform
)))
621 ((not (symbolp (car stepform
)))
622 (error "first component of stepform should be a symbol, not `%s'"
623 (prin1-to-string (car stepform
))))
624 ((> (length stepform
) 3)
625 (error "too many components in stepform `%s'"
626 (prin1-to-string stepform
))))
628 (let* ((var (car stepform
))
629 (oblist (cadr stepform
))
630 (resultform (caddr stepform
)))
634 (cons 'lambda
(cons (list var
) body
)))
637 (list (list var nil
))
641 (defmacro do-all-symbols
(stepform &rest body
)
642 "(do-all-symbols (VAR [RESULTFORM]) . BODY)
643 Is the same as (do-symbols (VAR obarray RESULTFORM) . BODY)."
646 (list (car stepform
) 'obarray
(cadr stepform
))
649 (defmacro loop
(&rest body
)
650 "(loop . BODY) repeats BODY indefinitely and does not return.
651 Normally BODY uses `throw' or `signal' to cause an exit.
652 The forms in BODY should be lists, as non-lists are reserved for new features."
653 ;; check that the body doesn't have atomic forms
655 (error "body of `loop' should be a list of lists or nil")
656 ;; ok, it is a list, check for atomic components
658 (function (lambda (component)
659 (if (nlistp component
)
660 (error "components of `loop' should be lists"))))
662 ;; build the infinite loop
663 (cons 'while
(cons 't body
))))
665 ;;;; end of cl-iterations.el
668 ;;;; This file provides some of the lists machinery of Common-Lisp
669 ;;;; in a way compatible with Emacs Lisp. Especially, see the the
670 ;;;; typical c[ad]*r functions.
672 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
673 ;;;; (quiroz@cs.rochester.edu)
675 (defvar *cl-valid-named-list-accessors
*
676 '(first rest second third fourth fifth sixth seventh eighth ninth tenth
))
677 (defvar *cl-valid-nth-offsets
*
688 (defun byte-compile-named-list-accessors (form)
689 "Generate code for (<accessor> FORM), where <accessor> is one of the named
690 list accessors: first, second, ..., tenth, rest."
691 (let* ((fun (car form
))
693 (valid *cl-valid-named-list-accessors
*)
694 (offsets *cl-valid-nth-offsets
*))
695 (if (or (null (cdr form
)) (cddr form
))
696 (error "%s needs exactly one argument, seen `%s'"
697 fun
(prin1-to-string form
)))
698 (if (not (memq fun valid
))
699 (error "`%s' not in {first, ..., tenth, rest}" fun
))
700 (cond ((eq fun
'first
)
701 (byte-compile-form arg
)
702 (setq byte-compile-depth
(1- byte-compile-depth
))
703 (byte-compile-out byte-car
0))
705 (byte-compile-form arg
)
706 (setq byte-compile-depth
(1- byte-compile-depth
))
707 (byte-compile-out byte-cdr
0))
708 (t ;one of the others
709 (byte-compile-constant (cdr (assoc fun offsets
)))
710 (byte-compile-form arg
)
711 (setq byte-compile-depth
(1- byte-compile-depth
))
712 (byte-compile-out byte-nth
0)
715 ;;; Synonyms for list functions
719 (put 'first
'byte-compile
'byte-compile-named-list-accessors
)
722 "Return the second element of the list LIST."
724 (put 'second
'byte-compile
'byte-compile-named-list-accessors
)
727 "Return the third element of the list LIST."
729 (put 'third
'byte-compile
'byte-compile-named-list-accessors
)
732 "Return the fourth element of the list LIST."
734 (put 'fourth
'byte-compile
'byte-compile-named-list-accessors
)
737 "Return the fifth element of the list LIST."
739 (put 'fifth
'byte-compile
'byte-compile-named-list-accessors
)
742 "Return the sixth element of the list LIST."
744 (put 'sixth
'byte-compile
'byte-compile-named-list-accessors
)
747 "Return the seventh element of the list LIST."
749 (put 'seventh
'byte-compile
'byte-compile-named-list-accessors
)
752 "Return the eighth element of the list LIST."
754 (put 'eighth
'byte-compile
'byte-compile-named-list-accessors
)
757 "Return the ninth element of the list LIST."
759 (put 'ninth
'byte-compile
'byte-compile-named-list-accessors
)
762 "Return the tenth element of the list LIST."
764 (put 'tenth
'byte-compile
'byte-compile-named-list-accessors
)
769 (put 'rest
'byte-compile
'byte-compile-named-list-accessors
)
772 "t if X is nil, nil if X is a cons; error otherwise."
775 (error "endp received a non-cons, non-null argument `%s'"
776 (prin1-to-string x
))))
779 "Returns the last link in the list LIST."
781 (error "arg to `last' must be a list"))
782 (do ((current-cons x
(cdr current-cons
))
783 (next-cons (cdr x
) (cdr next-cons
)))
784 ((endp next-cons
) current-cons
)))
786 (defun list-length (x) ;taken from CLtL sect. 15.2
787 "Returns the length of a non-circular list, or `nil' for a circular one."
789 (fast x
(cddr fast
)) ;fast pointer, leaps by 2
790 (slow x
(cdr slow
)) ;slow pointer, leaps by 1
791 (ready nil
)) ;indicates termination
794 (setq ready t
)) ;return n
797 (setq ready t
)) ;return n+1
798 ((and (eq fast slow
) (> n
0))
800 (setq ready t
)) ;return nil
802 (setq n
(+ n
2)))))) ;just advance counter
804 (defun butlast (list &optional n
)
805 "Return a new list like LIST but sans the last N elements.
806 N defaults to 1. If the list doesn't have N elements, nil is returned."
807 (if (null n
) (setq n
1))
808 (reverse (nthcdr n
(reverse list
))))
810 (defun list* (arg &rest others
)
811 "Return a new list containing the first arguments consed onto the last arg.
812 Thus, (list* 1 2 3 '(a b)) returns (1 2 3 a b)."
815 (let* ((allargs (cons arg others
))
816 (front (butlast allargs
))
817 (back (last allargs
)))
818 (rplacd (last front
) (car back
))
821 (defun adjoin (item list
)
822 "Return a list which contains ITEM but is otherwise like LIST.
823 If ITEM occurs in LIST, the value is LIST. Otherwise it is (cons ITEM LIST).
824 When comparing ITEM against elements, `eql' is used."
829 (defun ldiff (list sublist
)
830 "Return a new list like LIST but sans SUBLIST.
831 SUBLIST must be one of the links in LIST; otherwise the value is LIST itself."
833 (curcons list
(cdr curcons
)))
834 ((or (endp curcons
) (eq curcons sublist
))
836 (setq result
(cons (car curcons
) result
))))
838 ;;; The popular c[ad]*r functions and other list accessors.
840 ;;; To implement this efficiently, a new byte compile handler is used to
841 ;;; generate the minimal code, saving one function call.
843 (defun byte-compile-ca*d
*r
(form)
844 "Generate code for a (c[ad]+r argument). This realizes the various
845 combinations of car and cdr whose names are supported in this implementation.
846 To use this functionality for a given function,just give its name a
847 'byte-compile property of 'byte-compile-ca*d*r"
848 (let* ((fun (car form
))
850 (seq (mapcar (function (lambda (letter)
852 'byte-car
'byte-cdr
)))
853 (cdr (nreverse (cdr (append (symbol-name fun
) nil
)))))))
854 ;; SEQ is a list of byte-car and byte-cdr in the correct order.
856 (error "internal: `%s' cannot be compiled by byte-compile-ca*d*r"
857 (prin1-to-string form
)))
858 (if (or (null (cdr form
)) (cddr form
))
859 (error "%s needs exactly one argument, seen `%s'"
860 fun
(prin1-to-string form
)))
861 (byte-compile-form arg
)
862 (setq byte-compile-depth
(1- byte-compile-depth
))
863 ;; the rest of this code doesn't change the stack depth!
865 (byte-compile-out (car seq
) 0)
866 (setq seq
(cdr seq
)))))
869 "Return the car of the car of X."
871 (put 'caar
'byte-compile
'byte-compile-ca
*d
*r
)
874 "Return the car of the cdr of X."
876 (put 'cadr
'byte-compile
'byte-compile-ca
*d
*r
)
879 "Return the cdr of the car of X."
881 (put 'cdar
'byte-compile
'byte-compile-ca
*d
*r
)
884 "Return the cdr of the cdr of X."
886 (put 'cddr
'byte-compile
'byte-compile-ca
*d
*r
)
889 "Return the car of the car of the car of X."
891 (put 'caaar
'byte-compile
'byte-compile-ca
*d
*r
)
894 "Return the car of the car of the cdr of X."
896 (put 'caadr
'byte-compile
'byte-compile-ca
*d
*r
)
899 "Return the car of the cdr of the car of X."
901 (put 'cadar
'byte-compile
'byte-compile-ca
*d
*r
)
904 "Return the cdr of the car of the car of X."
906 (put 'cdaar
'byte-compile
'byte-compile-ca
*d
*r
)
909 "Return the car of the cdr of the cdr of X."
911 (put 'caddr
'byte-compile
'byte-compile-ca
*d
*r
)
914 "Return the cdr of the car of the cdr of X."
916 (put 'cdadr
'byte-compile
'byte-compile-ca
*d
*r
)
919 "Return the cdr of the cdr of the car of X."
921 (put 'cddar
'byte-compile
'byte-compile-ca
*d
*r
)
924 "Return the cdr of the cdr of the cdr of X."
926 (put 'cdddr
'byte-compile
'byte-compile-ca
*d
*r
)
929 "Return the car of the car of the car of the car of X."
930 (car (car (car (car X
)))))
931 (put 'caaaar
'byte-compile
'byte-compile-ca
*d
*r
)
934 "Return the car of the car of the car of the cdr of X."
935 (car (car (car (cdr X
)))))
936 (put 'caaadr
'byte-compile
'byte-compile-ca
*d
*r
)
939 "Return the car of the car of the cdr of the car of X."
940 (car (car (cdr (car X
)))))
941 (put 'caadar
'byte-compile
'byte-compile-ca
*d
*r
)
944 "Return the car of the cdr of the car of the car of X."
945 (car (cdr (car (car X
)))))
946 (put 'cadaar
'byte-compile
'byte-compile-ca
*d
*r
)
949 "Return the cdr of the car of the car of the car of X."
950 (cdr (car (car (car X
)))))
951 (put 'cdaaar
'byte-compile
'byte-compile-ca
*d
*r
)
954 "Return the car of the car of the cdr of the cdr of X."
955 (car (car (cdr (cdr X
)))))
956 (put 'caaddr
'byte-compile
'byte-compile-ca
*d
*r
)
959 "Return the car of the cdr of the car of the cdr of X."
960 (car (cdr (car (cdr X
)))))
961 (put 'cadadr
'byte-compile
'byte-compile-ca
*d
*r
)
964 "Return the cdr of the car of the car of the cdr of X."
965 (cdr (car (car (cdr X
)))))
966 (put 'cdaadr
'byte-compile
'byte-compile-ca
*d
*r
)
969 "Return the car of the cdr of the cdr of the car of X."
970 (car (cdr (cdr (car X
)))))
971 (put 'caddar
'byte-compile
'byte-compile-ca
*d
*r
)
974 "Return the cdr of the car of the cdr of the car of X."
975 (cdr (car (cdr (car X
)))))
976 (put 'cdadar
'byte-compile
'byte-compile-ca
*d
*r
)
979 "Return the cdr of the cdr of the car of the car of X."
980 (cdr (cdr (car (car X
)))))
981 (put 'cddaar
'byte-compile
'byte-compile-ca
*d
*r
)
984 "Return the car of the cdr of the cdr of the cdr of X."
985 (car (cdr (cdr (cdr X
)))))
986 (put 'cadddr
'byte-compile
'byte-compile-ca
*d
*r
)
989 "Return the cdr of the cdr of the car of the cdr of X."
990 (cdr (cdr (car (cdr X
)))))
991 (put 'cddadr
'byte-compile
'byte-compile-ca
*d
*r
)
994 "Return the cdr of the car of the cdr of the cdr of X."
995 (cdr (car (cdr (cdr X
)))))
996 (put 'cdaddr
'byte-compile
'byte-compile-ca
*d
*r
)
999 "Return the cdr of the cdr of the cdr of the car of X."
1000 (cdr (cdr (cdr (car X
)))))
1001 (put 'cdddar
'byte-compile
'byte-compile-ca
*d
*r
)
1004 "Return the cdr of the cdr of the cdr of the cdr of X."
1005 (cdr (cdr (cdr (cdr X
)))))
1006 (put 'cddddr
'byte-compile
'byte-compile-ca
*d
*r
)
1008 ;;; some inverses of the accessors are needed for setf purposes
1010 (defun setnth (n list newval
)
1011 "Set (nth N LIST) to NEWVAL. Returns NEWVAL."
1012 (rplaca (nthcdr n list
) newval
))
1014 (defun setnthcdr (n list newval
)
1015 "(setnthcdr N LIST NEWVAL) => NEWVAL
1016 As a side effect, sets the Nth cdr of LIST to NEWVAL."
1018 (error "N must be 0 or greater, not %d" n
))
1020 (rplaca list
(car newval
))
1021 (rplacd list
(cdr newval
))
1024 (rplacd (nthcdr (- n
1) list
) newval
))))
1026 ;;; A-lists machinery
1028 (defun acons (key item alist
)
1029 "Return a new alist with KEY paired with ITEM; otherwise like ALIST.
1030 Does not copy ALIST."
1031 (cons (cons key item
) alist
))
1033 (defun pairlis (keys data
&optional alist
)
1034 "Return a new alist with each elt of KEYS paired with an elt of DATA;
1035 optional 3rd arg ALIST is nconc'd at the end. KEYS and DATA must
1036 have the same length."
1037 (unless (= (length keys
) (length data
))
1038 (error "keys and data should be the same length"))
1039 (do* ;;collect keys and data in front of alist
1040 ((kptr keys
(cdr kptr
)) ;traverses the keys
1041 (dptr data
(cdr dptr
)) ;traverses the data
1042 (key (car kptr
) (car kptr
)) ;current key
1043 (item (car dptr
) (car dptr
)) ;current data item
1045 ((endp kptr
) result
)
1046 (setq result
(acons key item result
))))
1050 ;;;; Emacs Lisp provides many of the 'sequences' functionality of
1051 ;;;; Common Lisp. This file provides a few things that were left out.
1055 (defkeyword :test
"Used to designate positive (selection) tests.")
1056 (defkeyword :test-not
"Used to designate negative (rejection) tests.")
1057 (defkeyword :key
"Used to designate component extractions.")
1058 (defkeyword :predicate
"Used to define matching of sequence components.")
1059 (defkeyword :start
"Inclusive low index in sequence")
1060 (defkeyword :end
"Exclusive high index in sequence")
1061 (defkeyword :start1
"Inclusive low index in first of two sequences.")
1062 (defkeyword :start2
"Inclusive low index in second of two sequences.")
1063 (defkeyword :end1
"Exclusive high index in first of two sequences.")
1064 (defkeyword :end2
"Exclusive high index in second of two sequences.")
1065 (defkeyword :count
"Number of elements to affect.")
1066 (defkeyword :from-end
"T when counting backwards.")
1068 (defun some (pred seq
&rest moreseqs
)
1069 "Test PREDICATE on each element of SEQUENCE; is it ever non-nil?
1070 Extra args are additional sequences; PREDICATE gets one arg from each
1071 sequence and we advance down all the sequences together in lock-step.
1072 A sequence means either a list or a vector."
1073 (let ((args (reassemble-argslists (list* seq moreseqs
))))
1074 (do* ((ready nil
) ;flag: return when t
1075 (result nil
) ;resulting value
1076 (applyval nil
) ;result of applying pred once
1078 (cdr remaining
)) ;remaining argument sets
1079 (current (car remaining
) ;current argument set
1081 ((or ready
(endp remaining
)) result
)
1082 (setq applyval
(apply pred current
))
1085 (setq result applyval
)))))
1087 (defun every (pred seq
&rest moreseqs
)
1088 "Test PREDICATE on each element of SEQUENCE; is it always non-nil?
1089 Extra args are additional sequences; PREDICATE gets one arg from each
1090 sequence and we advance down all the sequences together in lock-step.
1091 A sequence means either a list or a vector."
1092 (let ((args (reassemble-argslists (list* seq moreseqs
))))
1093 (do* ((ready nil
) ;flag: return when t
1094 (result t
) ;resulting value
1095 (applyval nil
) ;result of applying pred once
1097 (cdr remaining
)) ;remaining argument sets
1098 (current (car remaining
) ;current argument set
1100 ((or ready
(endp remaining
)) result
)
1101 (setq applyval
(apply pred current
))
1104 (setq result nil
)))))
1106 (defun notany (pred seq
&rest moreseqs
)
1107 "Test PREDICATE on each element of SEQUENCE; is it always nil?
1108 Extra args are additional sequences; PREDICATE gets one arg from each
1109 sequence and we advance down all the sequences together in lock-step.
1110 A sequence means either a list or a vector."
1111 (let ((args (reassemble-argslists (list* seq moreseqs
))))
1112 (do* ((ready nil
) ;flag: return when t
1113 (result t
) ;resulting value
1114 (applyval nil
) ;result of applying pred once
1116 (cdr remaining
)) ;remaining argument sets
1117 (current (car remaining
) ;current argument set
1119 ((or ready
(endp remaining
)) result
)
1120 (setq applyval
(apply pred current
))
1123 (setq result nil
)))))
1125 (defun notevery (pred seq
&rest moreseqs
)
1126 "Test PREDICATE on each element of SEQUENCE; is it sometimes nil?
1127 Extra args are additional sequences; PREDICATE gets one arg from each
1128 sequence and we advance down all the sequences together in lock-step.
1129 A sequence means either a list or a vector."
1130 (let ((args (reassemble-argslists (list* seq moreseqs
))))
1131 (do* ((ready nil
) ;flag: return when t
1132 (result nil
) ;resulting value
1133 (applyval nil
) ;result of applying pred once
1135 (cdr remaining
)) ;remaining argument sets
1136 (current (car remaining
) ;current argument set
1138 ((or ready
(endp remaining
)) result
)
1139 (setq applyval
(apply pred current
))
1144 ;;; More sequence functions that don't need keyword arguments
1146 (defun concatenate (type &rest sequences
)
1147 "(concatenate TYPE &rest SEQUENCES) => a sequence
1148 The sequence returned is of type TYPE (must be 'list, 'string, or 'vector) and
1149 contains the concatenation of the elements of all the arguments, in the order
1151 (let ((sequences (append sequences
'(()))))
1154 (apply (function append
) sequences
))
1156 (apply (function concat
) sequences
))
1158 (apply (function vector
) (apply (function append
) sequences
)))
1160 (error "type for concatenate `%s' not 'list, 'string or 'vector"
1161 (prin1-to-string type
))))))
1163 (defun map (type function
&rest sequences
)
1164 "(map TYPE FUNCTION &rest SEQUENCES) => a sequence
1165 The FUNCTION is called on each set of elements from the SEQUENCES \(stopping
1166 when the shortest sequence is terminated\) and the results are possibly
1167 returned in a sequence of type TYPE \(one of 'list, 'vector, 'string, or nil\)
1168 giving NIL for TYPE gets rid of the values."
1169 (if (not (memq type
(list 'list
'string
'vector nil
)))
1170 (error "type for map `%s' not 'list, 'string, 'vector or nil"
1171 (prin1-to-string type
)))
1172 (let ((argslists (reassemble-argslists sequences
))
1175 (while argslists
;don't bother accumulating
1176 (apply function
(car argslists
))
1177 (setq argslists
(cdr argslists
)))
1178 (setq results
(mapcar (function (lambda (args) (apply function args
)))
1184 (funcall (function concat
) results
))
1186 (apply (function vector
) results
))))))
1188 ;;; an inverse of elt is needed for setf purposes
1190 (defun setelt (seq n newval
)
1191 "In SEQUENCE, set the Nth element to NEWVAL. Returns NEWVAL.
1192 A sequence means either a list or a vector."
1193 (let ((l (length seq
)))
1194 (if (or (< n
0) (>= n l
))
1195 (error "N(%d) should be between 0 and %d" n l
)
1196 ;; only two cases need be considered valid, as strings are arrays
1198 (setnth n seq newval
))
1200 (aset seq n newval
))
1202 (error "SEQ should be a sequence, not `%s'"
1203 (prin1-to-string seq
)))))))
1205 ;;; Testing with keyword arguments.
1207 ;;; Many of the sequence functions use keywords to denote some stylized
1208 ;;; form of selecting entries in a sequence. The involved arguments
1209 ;;; are collected with a &rest marker (as Emacs Lisp doesn't have a &key
1210 ;;; marker), then they are passed to build-klist, who
1211 ;;; constructs an association list. That association list is used to
1212 ;;; test for satisfaction and matching.
1214 ;;; DON'T USE MEMBER, NOR ANY FUNCTION THAT COULD TAKE KEYWORDS HERE!!!
1216 (defun build-klist (argslist acceptable
&optional allow-other-keys
)
1217 "Decode a keyword argument list ARGSLIST for keywords in ACCEPTABLE.
1218 ARGSLIST is a list, presumably the &rest argument of a call, whose
1219 even numbered elements must be keywords.
1220 ACCEPTABLE is a list of keywords, the only ones that are truly acceptable.
1221 The result is an alist containing the arguments named by the keywords
1222 in ACCEPTABLE, or an error is signalled, if something failed.
1223 If the third argument (an optional) is non-nil, other keys are acceptable."
1224 ;; check legality of the arguments, then destructure them
1225 (unless (and (listp argslist
)
1226 (evenp (length argslist
)))
1227 (error "build-klist: odd number of keyword-args"))
1228 (unless (and (listp acceptable
)
1229 (every 'keywordp acceptable
))
1230 (error "build-klist: second arg should be a list of keywords"))
1231 (multiple-value-bind
1233 (unzip-list argslist
)
1234 (unless (every 'keywordp keywords
)
1235 (error "build-klist: expected keywords, found `%s'"
1236 (prin1-to-string keywords
)))
1237 (unless (or allow-other-keys
1238 (every (function (lambda (keyword)
1239 (memq keyword acceptable
)))
1241 (error "bad keyword[s]: %s not in %s"
1242 (prin1-to-string (mapcan (function (lambda (keyword)
1243 (if (memq keyword acceptable
)
1247 (prin1-to-string acceptable
)))
1248 (do* ;;pick up the pieces
1249 ((auxlist ;auxiliary a-list, may
1250 (pairlis keywords forms
)) ;contain repetitions and junk
1251 (ptr acceptable
(cdr ptr
)) ;pointer in acceptable
1252 (this (car ptr
) (car ptr
)) ;current acceptable keyword
1253 (auxval nil
) ;used to move values around
1254 (alist '())) ;used to build the result
1256 ;; if THIS appears in auxlist, use its value
1257 (when (setq auxval
(assq this auxlist
))
1258 (setq alist
(cons auxval alist
))))))
1261 (defun extract-from-klist (klist key
&optional default
)
1262 "(extract-from-klist KLIST KEY [DEFAULT]) => value of KEY or DEFAULT
1263 Extract value associated with KEY in KLIST (return DEFAULT if nil)."
1264 (let ((retrieved (cdr (assq key klist
))))
1265 (or retrieved default
)))
1267 (defun keyword-argument-supplied-p (klist key
)
1268 "(keyword-argument-supplied-p KLIST KEY) => nil or something
1269 NIL if KEY (a keyword) does not appear in the KLIST."
1272 (defun add-to-klist (key item klist
)
1273 "(ADD-TO-KLIST KEY ITEM KLIST) => new KLIST
1274 Add association (KEY . ITEM) to KLIST."
1275 (setq klist
(acons key item klist
)))
1277 (defun elt-satisfies-test-p (item elt klist
)
1278 "(elt-satisfies-test-p ITEM ELT KLIST) => t or nil
1279 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1280 True if the given ITEM and ELT satisfy the test."
1281 (let ((test (extract-from-klist klist
:test
))
1282 (test-not (extract-from-klist klist
:test-not
))
1283 (keyfn (extract-from-klist klist
:key
'identity
)))
1285 (funcall test item
(funcall keyfn elt
)))
1287 (not (funcall test-not item
(funcall keyfn elt
))))
1288 (t ;should never happen
1289 (error "neither :test nor :test-not in `%s'"
1290 (prin1-to-string klist
))))))
1292 (defun elt-satisfies-if-p (item klist
)
1293 "(elt-satisfies-if-p ITEM KLIST) => t or nil
1294 True if an -if style function was called and ITEM satisfies the
1295 predicate under :predicate in KLIST."
1296 (let ((predicate (extract-from-klist klist
:predicate
))
1297 (keyfn (extract-from-klist klist
:key
'identity
)))
1298 (funcall predicate item
(funcall keyfn elt
))))
1300 (defun elt-satisfies-if-not-p (item klist
)
1301 "(elt-satisfies-if-not-p ITEM KLIST) => t or nil
1302 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1303 True if an -if-not style function was called and ITEM does not satisfy
1304 the predicate under :predicate in KLIST."
1305 (let ((predicate (extract-from-klist klist
:predicate
))
1306 (keyfn (extract-from-klist klist
:key
'identity
)))
1307 (not (funcall predicate item
(funcall keyfn elt
)))))
1309 (defun elts-match-under-klist-p (e1 e2 klist
)
1310 "(elts-match-under-klist-p E1 E2 KLIST) => t or nil
1311 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1312 True if elements E1 and E2 match under the tests encoded in KLIST."
1313 (let ((test (extract-from-klist klist
:test
))
1314 (test-not (extract-from-klist klist
:test-not
))
1315 (keyfn (extract-from-klist klist
:key
'identity
)))
1316 (if (and test test-not
)
1317 (error "both :test and :test-not in `%s'"
1318 (prin1-to-string klist
)))
1320 (funcall test
(funcall keyfn e1
) (funcall keyfn e2
)))
1322 (not (funcall test-not
(funcall keyfn e1
) (funcall keyfn e2
))))
1323 (t ;should never happen
1324 (error "neither :test nor :test-not in `%s'"
1325 (prin1-to-string klist
))))))
1327 ;;; This macro simplifies using keyword args. It is less clumsy than using
1328 ;;; the primitives build-klist, etc... For instance, member could be written
1331 ;;; (defun member (item list &rest kargs)
1332 ;;; (with-keyword-args kargs (test test-not (key 'identity))
1335 ;;; Suggested by Robert Potter (potter@cs.rochester.edu, 15 Nov 1989)
1337 (defmacro with-keyword-args
(keyargslist vardefs
&rest body
)
1338 "(WITH-KEYWORD-ARGS KEYARGSLIST VARDEFS . BODY)
1339 KEYARGSLIST can be either a symbol or a list of one or two symbols.
1340 In the second case, the second symbol is either T or NIL, indicating whether
1341 keywords other than the mentioned ones are tolerable.
1343 VARDEFS is a list. Each entry is either a VAR (symbol) or matches
1344 \(VAR [DEFAULT [KEYWORD]]). Just giving VAR is the same as giving
1347 The BODY is executed in an environment where each VAR (a symbol) is bound to
1348 the value present in the KEYARGSLIST provided, or to the DEFAULT. The value
1349 is searched by using the keyword form of VAR (i.e., :VAR) or the optional
1350 keyword if provided.
1352 Notice that this macro doesn't distinguish between a default value given
1353 explicitly by the user and one provided by default. See also the more
1354 primitive functions build-klist, add-to-klist, extract-from-klist,
1355 keyword-argument-supplied-p, elt-satisfies-test-p, elt-satisfies-if-p,
1356 elt-satisfies-if-not-p, elts-match-under-klist-p. They provide more complete,
1357 if clumsier, control over this feature."
1358 (let (allow-other-keys)
1359 (if (listp keyargslist
)
1360 (if (> (length keyargslist
) 2)
1362 "`%s' should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1363 (prin1-to-string keyargslist
))
1364 (setq allow-other-keys
(cadr keyargslist
)
1365 keyargslist
(car keyargslist
))
1367 (symbolp keyargslist
)
1368 (memq allow-other-keys
'(t nil
))))
1370 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1372 (if (symbolp keyargslist
)
1373 (setq allow-other-keys nil
)
1375 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)")))
1376 (let (vars defaults keywords forms
1377 (klistname (gensym "KLIST_")))
1378 (mapcar (function (lambda (entry)
1379 (if (symbolp entry
) ;defaulty case
1380 (setq entry
(list entry nil
(keyword-of entry
))))
1381 (let* ((l (length entry
))
1385 (if (or (< l
1) (> l
3))
1387 "`%s' must match (VAR [DEFAULT [KEYWORD]])"
1388 (prin1-to-string entry
)))
1389 (if (or (null v
) (not (symbolp v
)))
1391 "bad variable `%s': must be non-null symbol"
1392 (prin1-to-string v
)))
1393 (setq vars
(cons v vars
))
1394 (setq defaults
(cons d defaults
))
1396 (setq k
(keyword-of v
)))
1399 (not (keywordp k
))))
1401 "bad keyword `%s'" (prin1-to-string k
)))
1402 (setq keywords
(cons k keywords
))
1403 (setq forms
(cons (list v
(list 'extract-from-klist
1410 (list 'let
* (nconc (list (list klistname
1411 (list 'build-klist keyargslist
1412 (list 'quote keywords
)
1416 (put 'with-keyword-args
'lisp-indent-function
1)
1420 ;;; It is here mostly as an example of how to use KLISTs.
1422 ;;; First of all, you need to declare the keywords (done elsewhere in this
1424 ;;; (defkeyword :from-end "syntax of sequence functions")
1425 ;;; (defkeyword :start "syntax of sequence functions")
1428 ;;; Then, you capture all the possible keyword arguments with a &rest
1429 ;;; argument. You can pass that list downward again, of course, but
1430 ;;; internally you need to parse it into a KLIST (an alist, really). One uses
1431 ;;; (build-klist REST-ARGS ACCEPTABLE-KEYWORDS [ALLOW-OTHER]). You can then
1432 ;;; test for presence by using (keyword-argument-supplied-p KLIST KEY) and
1433 ;;; extract a value with (extract-from-klist KLIST KEY [DEFAULT]).
1435 (defun reduce (function sequence
&rest kargs
)
1436 "Apply FUNCTION (a function of two arguments) to succesive pairs of elements
1437 from SEQUENCE. Some keyword arguments are valid after FUNCTION and SEQUENCE:
1438 :from-end If non-nil, process the values backwards
1439 :initial-value If given, prefix it to the SEQUENCE. Suffix, if :from-end
1440 :start Restrict reduction to the subsequence from this index
1441 :end Restrict reduction to the subsequence BEFORE this index.
1442 If the sequence is empty and no :initial-value is given, the FUNCTION is
1443 called on zero (not two) arguments. Otherwise, if there is exactly one
1444 element in the combination of SEQUENCE and the initial value, that element is
1446 (let* ((klist (build-klist kargs
'(:from-end
:start
:end
:initial-value
)))
1447 (length (length sequence
))
1448 (from-end (extract-from-klist klist
:from-end
))
1449 (initial-value-given (keyword-argument-supplied-p
1450 klist
:initial-value
))
1451 (start (extract-from-klist kargs
:start
0))
1452 (end (extract-from-klist kargs
:end length
)))
1453 (setq sequence
(cl$subseq-as-list sequence start end
))
1455 (setq sequence
(reverse sequence
)))
1456 (if initial-value-given
1457 (setq sequence
(cons (extract-from-klist klist
:initial-value
)
1460 (funcall function
) ;only use of 0 arguments
1461 (let* ((result (car sequence
))
1462 (sequence (cdr sequence
)))
1464 (setq result
(if from-end
1465 (funcall function
(car sequence
) result
)
1466 (funcall function result
(car sequence
)))
1467 sequence
(cdr sequence
)))
1470 (defun cl$subseq-as-list
(sequence start end
)
1471 "(cl$subseq-as-list SEQUENCE START END) => a list"
1472 (let ((list (append sequence nil
))
1473 (length (length sequence
))
1476 (error "start should be >= 0, not %d" start
))
1478 (error "end should be <= %d, not %d" length end
))
1479 (if (and (zerop start
) (= end length
))
1482 (vector (apply 'vector list
)))
1484 (setq result
(cons (elt vector i
) result
))
1486 (nreverse result
)))))
1488 ;;;; end of cl-sequences.el
1490 ;;;; Some functions with keyword arguments
1492 ;;;; Both list and sequence functions are considered here together. This
1493 ;;;; doesn't fit any more with the original split of functions in files.
1495 (defun member (item list
&rest kargs
)
1496 "Look for ITEM in LIST; return first tail of LIST the car of whose first
1497 cons cell tests the same as ITEM. Admits arguments :key, :test, and :test-not."
1498 (if (null kargs
) ;treat this fast for efficiency
1500 (let* ((klist (build-klist kargs
'(:test
:test-not
:key
)))
1501 (test (extract-from-klist klist
:test
))
1502 (testnot (extract-from-klist klist
:test-not
))
1503 (key (extract-from-klist klist
:key
'identity
)))
1504 ;; another workaround allegledly for speed
1505 (if (and (or (eq test
'eq
) (eq test
'eql
)
1506 (eq test
(symbol-function 'eq
))
1507 (eq test
(symbol-function 'eql
)))
1509 (or (eq key
'identity
) ;either by default or so given
1510 (eq key
(function identity
)) ;could this happen?
1511 (eq key
(symbol-function 'identity
)) ;sheer paranoia
1514 (if (and test testnot
)
1515 (error ":test and :test-not both specified for member"))
1516 (if (not (or test testnot
))
1518 ;; final hack: remove the indirection through the function names
1520 (if (symbolp testnot
)
1521 (setq testnot
(symbol-function testnot
)))
1523 (setq test
(symbol-function test
))))
1525 (setq key
(symbol-function key
)))
1531 (while (not (or done
(endp ptr
)))
1532 (cond ((not (funcall testnot item
(funcall key
(car ptr
))))
1535 (setq ptr
(cdr ptr
)))
1536 (while (not (or done
(endp ptr
)))
1537 (cond ((funcall test item
(funcall key
(car ptr
)))
1540 (setq ptr
(cdr ptr
))))
1543 ;;;; MULTIPLE VALUES
1544 ;;;; This package approximates the behavior of the multiple-values
1545 ;;;; forms of Common Lisp.
1547 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1548 ;;;; (quiroz@cs.rochester.edu)
1550 ;;; Lisp indentation information
1551 (put 'multiple-value-bind
'lisp-indent-function
2)
1552 (put 'multiple-value-setq
'lisp-indent-function
2)
1553 (put 'multiple-value-list
'lisp-indent-function nil
)
1554 (put 'multiple-value-call
'lisp-indent-function
1)
1555 (put 'multiple-value-prog1
'lisp-indent-function
1)
1557 ;;; Global state of the package is kept here
1558 (defvar *mvalues-values
* nil
1559 "Most recently returned multiple-values")
1560 (defvar *mvalues-count
* nil
1561 "Count of multiple-values returned, or nil if the mechanism was not used")
1563 ;;; values is the standard multiple-value-return form. Must be the
1564 ;;; last thing evaluated inside a function. If the caller is not
1565 ;;; expecting multiple values, only the first one is passed. (values)
1566 ;;; is the same as no-values returned (unaware callers see nil). The
1567 ;;; alternative (values-list <list>) is just a convenient shorthand
1568 ;;; and complements multiple-value-list.
1570 (defun values (&rest val-forms
)
1571 "Produce multiple values (zero or more). Each arg is one value.
1572 See also `multiple-value-bind', which is one way to examine the
1573 multiple values produced by a form. If the containing form or caller
1574 does not check specially to see multiple values, it will see only
1576 (setq *mvalues-values
* val-forms
)
1577 (setq *mvalues-count
* (length *mvalues-values
*))
1578 (car *mvalues-values
*))
1580 (defun values-list (&optional val-forms
)
1581 "Produce multiple values (zero or mode). Each element of LIST is one value.
1582 This is equivalent to (apply 'values LIST)."
1583 (cond ((nlistp val-forms
)
1584 (error "Argument to values-list must be a list, not `%s'"
1585 (prin1-to-string val-forms
))))
1586 (setq *mvalues-values
* val-forms
)
1587 (setq *mvalues-count
* (length *mvalues-values
*))
1588 (car *mvalues-values
*))
1590 ;;; Callers that want to see the multiple values use these macros.
1592 (defmacro multiple-value-list
(form)
1593 "Execute FORM and return a list of all the (multiple) values FORM produces.
1594 See `values' and `multiple-value-bind'."
1596 (list 'setq
'*mvalues-count
* nil
)
1597 (list 'let
(list (list 'it
'(gensym)))
1598 (list 'set
'it form
)
1599 (list 'if
'*mvalues-count
*
1600 (list 'copy-sequence
'*mvalues-values
*)
1602 (list 'setq
'*mvalues-count
* 1)
1603 (list 'setq
'*mvalues-values
*
1604 (list 'list
(list 'symbol-value
'it
)))
1605 (list 'copy-sequence
'*mvalues-values
*))))))
1607 (defmacro multiple-value-call
(function &rest args
)
1608 "Call FUNCTION on all the values produced by the remaining arguments.
1609 (multiple-value-call '+ (values 1 2) (values 3 4)) is 10."
1610 (let* ((result (gentemp))
1612 (list 'apply
(list 'function
(eval function
))
1613 (list 'let
* (list (list result
'()))
1614 (list 'dolist
(list arg
(list 'quote args
) result
)
1618 (list 'multiple-value-list
1619 (list 'eval arg
)))))))))
1621 (defmacro multiple-value-bind
(vars form
&rest body
)
1622 "Bind VARS to the (multiple) values produced by FORM, then do BODY.
1623 VARS is a list of variables; each is bound to one of FORM's values.
1624 If FORM doesn't make enough values, the extra variables are bound to nil.
1625 (Ordinary forms produce only one value; to produce more, use `values'.)
1626 Extra values are ignored.
1627 BODY (zero or more forms) is executed with the variables bound,
1628 then the bindings are unwound."
1629 (let* ((vals (gentemp)) ;name for intermediate values
1630 (clauses (mv-bind-clausify ;convert into clauses usable
1631 vars vals
))) ; in a let form
1633 (cons (list vals
(list 'multiple-value-list form
))
1637 (defmacro multiple-value-setq
(vars form
)
1638 "Set VARS to the (multiple) values produced by FORM.
1639 VARS is a list of variables; each is set to one of FORM's values.
1640 If FORM doesn't make enough values, the extra variables are set to nil.
1641 (Ordinary forms produce only one value; to produce more, use `values'.)
1642 Extra values are ignored."
1643 (let* ((vals (gentemp)) ;name for intermediate values
1644 (clauses (mv-bind-clausify ;convert into clauses usable
1645 vars vals
))) ; in a setq (after append).
1647 (list (list vals
(list 'multiple-value-list form
)))
1648 (cons 'setq
(apply (function append
) clauses
)))))
1650 (defmacro multiple-value-prog1
(form &rest body
)
1651 "Evaluate FORM, then BODY, then produce the same values FORM produced.
1652 Thus, (multiple-value-prog1 (values 1 2) (foobar)) produces values 1 and 2.
1653 This is like `prog1' except that `prog1' would produce only one value,
1654 which would be the first of FORM's values."
1655 (let* ((heldvalues (gentemp)))
1657 (cons (list (list heldvalues
(list 'multiple-value-list form
)))
1658 (append body
(list (list 'values-list heldvalues
)))))))
1660 ;;; utility functions
1662 ;;; mv-bind-clausify makes the pairs needed to have the variables in
1663 ;;; the variable list correspond with the values returned by the form.
1664 ;;; vals is a fresh symbol that intervenes in all the bindings.
1666 (defun mv-bind-clausify (vars vals
)
1667 "MV-BIND-CLAUSIFY VARS VALS => Auxiliary list
1668 Forms a list of pairs `(,(nth i vars) (nth i vals)) for i from 0 to
1669 the length of VARS (a list of symbols). VALS is just a fresh symbol."
1670 (if (or (nlistp vars
)
1671 (notevery 'symbolp vars
))
1672 (error "expected a list of symbols, not `%s'"
1673 (prin1-to-string vars
)))
1674 (let* ((nvars (length vars
))
1676 (dotimes (n nvars clauses
)
1677 (setq clauses
(cons (list (nth n vars
)
1678 (list 'nth n vals
)) clauses
)))))
1680 ;;;; end of cl-multiple-values.el
1683 ;;;; This file provides integer arithmetic extensions. Although
1684 ;;;; Emacs Lisp doesn't really support anything but integers, that
1685 ;;;; has still to be made to look more or less standard.
1688 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1689 ;;;; (quiroz@cs.rochester.edu)
1692 (defun plusp (number)
1693 "True if NUMBER is strictly greater than zero."
1696 (defun minusp (number)
1697 "True if NUMBER is strictly less than zero."
1700 (defun oddp (number)
1701 "True if INTEGER is not divisible by 2."
1702 (/= (% number
2) 0))
1704 (defun evenp (number)
1705 "True if INTEGER is divisible by 2."
1709 "Return the absolute value of NUMBER."
1714 (defun signum (number)
1715 "Return -1, 0 or 1 according to the sign of NUMBER."
1723 (defun gcd (&rest integers
)
1724 "Return the greatest common divisor of all the arguments.
1725 The arguments must be integers. With no arguments, value is zero."
1726 (let ((howmany (length integers
)))
1727 (cond ((= howmany
0)
1730 (abs (car integers
)))
1732 (apply (function gcd
)
1733 (cons (gcd (nth 0 integers
) (nth 1 integers
))
1734 (nthcdr 2 integers
))))
1736 ;; essentially the euclidean algorithm
1737 (when (zerop (* (nth 0 integers
) (nth 1 integers
)))
1738 (error "a zero argument is invalid for `gcd'"))
1739 (do* ((absa (abs (nth 0 integers
))) ; better to operate only
1740 (absb (abs (nth 1 integers
))) ;on positives.
1741 (dd (max absa absb
)) ; setup correct order for the
1742 (ds (min absa absb
)) ;succesive divisions.
1743 ;; intermediate results
1747 (done nil
) ; flag: end of iterations
1748 (result 0)) ; final value
1752 (cond ((zerop r
) (setq done t
) (setq result ds
))
1753 (t (setq dd ds
) (setq ds r
))))))))
1755 (defun lcm (integer &rest more
)
1756 "Return the least common multiple of all the arguments.
1757 The arguments must be integers and there must be at least one of them."
1758 (let ((howmany (length more
))
1761 prod
; intermediate product
1762 (yetmore (nthcdr 1 more
)))
1763 (cond ((zerop howmany
)
1765 ((> howmany
1) ; recursive case
1766 (apply (function lcm
)
1767 (cons (lcm a b
) yetmore
)))
1768 (t ; base case, just 2 args
1774 (/ (abs prod
) (gcd a b
))))))))
1776 (defun isqrt (number)
1777 "Return the integer square root of NUMBER.
1778 NUMBER must not be negative. Result is largest integer less than or
1779 equal to the real square root of the argument."
1780 ;; The method used here is essentially the Newtonian iteration
1781 ;; x[n+1] <- (x[n] + Number/x[n]) / 2
1782 ;; suitably adapted to integer arithmetic.
1783 ;; Thanks to Philippe Schnoebelen <phs@lifia.imag.fr> for suggesting the
1784 ;; termination condition.
1785 (cond ((minusp number
)
1786 (error "argument to `isqrt' (%d) must not be negative"
1790 (t ;so (>= number 0)
1791 (do* ((approx 1) ;any positive integer will do
1792 (new 0) ;init value irrelevant
1794 (done (if (> (* approx approx
) number
)
1797 (setq new
(/ (+ approx
(/ number approx
)) 2)
1798 done
(or (= new approx
) (= new
(+ approx
1)))
1801 (defun floor (number &optional divisor
)
1802 "Divide DIVIDEND by DIVISOR, rounding toward minus infinity.
1803 DIVISOR defaults to 1. The remainder is produced as a second value."
1805 ((and (null divisor
) ; trivial case
1808 (t ; do the division
1809 (multiple-value-bind
1811 (safe-idiv number divisor
)
1816 (t ;opposite-signs case
1819 (let ((q (- (+ q
1))))
1820 (values q
(- number
(* q divisor
)))))))))))
1822 (defun ceiling (number &optional divisor
)
1823 "Divide DIVIDEND by DIVISOR, rounding toward plus infinity.
1824 DIVISOR defaults to 1. The remainder is produced as a second value."
1826 ((and (null divisor
) ; trivial case
1829 (t ; do the division
1830 (multiple-value-bind
1832 (safe-idiv number divisor
)
1836 (values (+ q
1) (- r divisor
)))
1838 (values (- q
) (+ number
(* q divisor
)))))))))
1840 (defun truncate (number &optional divisor
)
1841 "Divide DIVIDEND by DIVISOR, rounding toward zero.
1842 DIVISOR defaults to 1. The remainder is produced as a second value."
1844 ((and (null divisor
) ; trivial case
1847 (t ; do the division
1848 (multiple-value-bind
1850 (safe-idiv number divisor
)
1853 ((plusp s
) ;same as floor
1856 (values (- q
) (+ number
(* q divisor
)))))))))
1858 (defun round (number &optional divisor
)
1859 "Divide DIVIDEND by DIVISOR, rounding to nearest integer.
1860 DIVISOR defaults to 1. The remainder is produced as a second value."
1861 (cond ((and (null divisor
) ; trivial case
1864 (t ; do the division
1865 (multiple-value-bind
1867 (safe-idiv number divisor
)
1869 ;; adjust magnitudes first, and then signs
1870 (let ((other-r (- (abs divisor
) r
)))
1871 (cond ((> r other-r
)
1875 ;; round to even is mandatory
1878 (setq r
(- number
(* q divisor
)))
1881 (defun mod (number divisor
)
1882 "Return remainder of X by Y (rounding quotient toward minus infinity).
1883 That is, the remainder goes with the quotient produced by `floor'."
1884 (multiple-value-bind (q r
) (floor number divisor
)
1887 (defun rem (number divisor
)
1888 "Return remainder of X by Y (rounding quotient toward zero).
1889 That is, the remainder goes with the quotient produced by `truncate'."
1890 (multiple-value-bind (q r
) (truncate number divisor
)
1893 ;;; internal utilities
1895 ;;; safe-idiv performs an integer division with positive numbers only.
1896 ;;; It is known that some machines/compilers implement weird remainder
1897 ;;; computations when working with negatives, so the idea here is to
1898 ;;; make sure we know what is coming back to the caller in all cases.
1900 ;;; Signum computation fixed by mad@math.keio.JUNET (MAEDA Atusi)
1902 (defun safe-idiv (a b
)
1903 "SAFE-IDIV A B => Q R S
1904 Q=|A|/|B|, R is the rest, S is the sign of A/B."
1905 (unless (and (numberp a
) (numberp b
))
1906 (error "arguments to `safe-idiv' must be numbers"))
1908 (error "cannot divide %d by zero" a
))
1909 (let* ((absa (abs a
))
1912 (s (* (signum a
) (signum b
)))
1913 (r (- a
(* (* s q
) b
))))
1916 ;;;; end of cl-arith.el
1919 ;;;; This file provides the setf macro and friends. The purpose has
1920 ;;;; been modest, only the simplest defsetf forms are accepted.
1921 ;;;; Use it and enjoy.
1923 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1924 ;;;; (quiroz@cs.rochester.edu)
1927 (defkeyword :setf-update-fn
1928 "Property, its value is the function setf must invoke to update a
1929 generalized variable whose access form is a function call of the
1930 symbol that has this property.")
1932 (defkeyword :setf-update-doc
1933 "Property of symbols that have a `defsetf' update function on them,
1934 installed by the `defsetf' from its optional third argument.")
1936 (defmacro setf
(&rest pairs
)
1937 "Generalized `setq' that can set things other than variable values.
1938 A use of `setf' looks like (setf {PLACE VALUE}...).
1939 The behavior of (setf PLACE VALUE) is to access the generalized variable
1940 at PLACE and store VALUE there. It returns VALUE. If there is more
1941 than one PLACE and VALUE, each PLACE is set from its VALUE before
1942 the next PLACE is evaluated."
1943 (let ((nforms (length pairs
)))
1944 ;; check the number of subforms
1945 (cond ((/= (% nforms
2) 0)
1946 (error "odd number of arguments to `setf'"))
1950 ;; this is the recursive case
1952 (do* ;collect the place-value pairs
1953 ((args pairs
(cddr args
))
1954 (place (car args
) (car args
))
1955 (value (cadr args
) (cadr args
))
1957 ((endp args
) (nreverse result
))
1959 (cons (list 'setf place value
)
1962 ;; this is the base case (SETF PLACE VALUE)
1963 (let* ((place (car pairs
))
1964 (value (cadr pairs
))
1967 ;; dispatch on the type of the PLACE
1968 (cond ((symbolp place
)
1969 (list 'setq place value
))
1971 (setq head
(car place
))
1973 (setq updatefn
(get head
:setf-update-fn
)))
1974 (if (or (and (consp updatefn
) (eq (car updatefn
) 'lambda
))
1975 (and (symbolp updatefn
)
1977 (let ((defn (symbol-function updatefn
)))
1980 (eq (car defn
) 'lambda
))))))
1981 (cons updatefn
(append (cdr place
) (list value
)))
1982 (multiple-value-bind
1984 (pair-with-newsyms (append (cdr place
) (list value
)))
1985 ;; this let gets new symbols to ensure adequate
1986 ;; order of evaluation of the subforms.
1989 (cons updatefn newsyms
)))))
1991 (error "no `setf' update-function for `%s'"
1992 (prin1-to-string place
)))))))))
1994 (defmacro defsetf
(accessfn updatefn
&optional docstring
)
1995 "Define how `setf' works on a certain kind of generalized variable.
1996 A use of `defsetf' looks like (defsetf ACCESSFN UPDATEFN [DOCSTRING]).
1997 ACCESSFN is a symbol. UPDATEFN is a function or macro which takes
1998 one more argument than ACCESSFN does. DEFSETF defines the translation
1999 of (SETF (ACCESFN . ARGS) NEWVAL) to be a form like (UPDATEFN ARGS... NEWVAL).
2000 The function UPDATEFN must return its last arg, after performing the
2001 updating called for."
2002 ;; reject ill-formed requests. too bad one can't test for functionp
2004 (when (not (symbolp accessfn
))
2005 (error "first argument of `defsetf' must be a symbol, not `%s'"
2006 (prin1-to-string accessfn
)))
2007 ;; update properties
2009 (list 'put
(list 'quote accessfn
)
2010 :setf-update-fn
(list 'function updatefn
))
2011 (list 'put
(list 'quote accessfn
) :setf-update-doc docstring
)
2012 ;; any better thing to return?
2013 (list 'quote accessfn
)))
2015 ;;; This section provides the "default" setfs for Common-Emacs-Lisp
2016 ;;; The user will not normally add anything to this, although
2017 ;;; defstruct will introduce new ones as a matter of fact.
2019 ;;; Apply is a special case. The Common Lisp
2020 ;;; standard makes the case of apply be useful when the user writes
2021 ;;; something like (apply #'name ...), Emacs Lisp doesn't have the #
2022 ;;; stuff, but it has (function ...). Notice that V18 includes a new
2023 ;;; apply: this file is compatible with V18 and pre-V18 Emacses.
2025 ;;; INCOMPATIBILITY: the SETF macro evaluates its arguments in the
2026 ;;; (correct) left to right sequence *before* checking for apply
2027 ;;; methods (which should really be an special case inside setf). Due
2028 ;;; to this, the lambda expression defsetf'd to apply will succeed in
2029 ;;; applying the right function even if the name was not quoted, but
2030 ;;; computed! That extension is not Common Lisp (nor is particularly
2031 ;;; useful, I think).
2034 (lambda (&rest args
)
2035 ;; dissasemble the calling form
2036 ;; "(((quote fn) x1 x2 ... xn) val)" (function instead of quote, too)
2037 (let* ((fnform (car args
)) ;functional form
2038 (applyargs (append ;arguments "to apply fnform"
2039 (apply 'list
* (butlast (cdr args
)))
2041 (newupdater nil
)) ; its update-fn, if any
2042 (if (and (symbolp fnform
)
2043 (setq newupdater
(get fnform
:setf-update-fn
)))
2044 (apply newupdater applyargs
)
2045 (error "can't `setf' to `%s'"
2046 (prin1-to-string fnform
)))))
2047 "`apply' is a special case for `setf'")
2052 "`setf' inversion for `aref'")
2056 "`setf' inversion for `nth'")
2060 "`setf' inversion for `nthcdr'")
2064 "`setf' inversion for `elt'")
2067 (lambda (list val
) (setnth 0 list val
))
2068 "`setf' inversion for `first'")
2071 (lambda (list val
) (setnth 1 list val
))
2072 "`setf' inversion for `second'")
2075 (lambda (list val
) (setnth 2 list val
))
2076 "`setf' inversion for `third'")
2079 (lambda (list val
) (setnth 3 list val
))
2080 "`setf' inversion for `fourth'")
2083 (lambda (list val
) (setnth 4 list val
))
2084 "`setf' inversion for `fifth'")
2087 (lambda (list val
) (setnth 5 list val
))
2088 "`setf' inversion for `sixth'")
2091 (lambda (list val
) (setnth 6 list val
))
2092 "`setf' inversion for `seventh'")
2095 (lambda (list val
) (setnth 7 list val
))
2096 "`setf' inversion for `eighth'")
2099 (lambda (list val
) (setnth 8 list val
))
2100 "`setf' inversion for `ninth'")
2103 (lambda (list val
) (setnth 9 list val
))
2104 "`setf' inversion for `tenth'")
2107 (lambda (list val
) (setcdr list val
))
2108 "`setf' inversion for `rest'")
2110 (defsetf car setcar
"Replace the car of a cons")
2112 (defsetf cdr setcdr
"Replace the cdr of a cons")
2115 (lambda (list val
) (setcar (nth 0 list
) val
))
2116 "`setf' inversion for `caar'")
2119 (lambda (list val
) (setcar (cdr list
) val
))
2120 "`setf' inversion for `cadr'")
2123 (lambda (list val
) (setcdr (car list
) val
))
2124 "`setf' inversion for `cdar'")
2127 (lambda (list val
) (setcdr (cdr list
) val
))
2128 "`setf' inversion for `cddr'")
2131 (lambda (list val
) (setcar (caar list
) val
))
2132 "`setf' inversion for `caaar'")
2135 (lambda (list val
) (setcar (cadr list
) val
))
2136 "`setf' inversion for `caadr'")
2139 (lambda (list val
) (setcar (cdar list
) val
))
2140 "`setf' inversion for `cadar'")
2143 (lambda (list val
) (setcdr (caar list
) val
))
2144 "`setf' inversion for `cdaar'")
2147 (lambda (list val
) (setcar (cddr list
) val
))
2148 "`setf' inversion for `caddr'")
2151 (lambda (list val
) (setcdr (cadr list
) val
))
2152 "`setf' inversion for `cdadr'")
2155 (lambda (list val
) (setcdr (cdar list
) val
))
2156 "`setf' inversion for `cddar'")
2159 (lambda (list val
) (setcdr (cddr list
) val
))
2160 "`setf' inversion for `cdddr'")
2163 (lambda (list val
) (setcar (caaar list
) val
))
2164 "`setf' inversion for `caaaar'")
2167 (lambda (list val
) (setcar (caadr list
) val
))
2168 "`setf' inversion for `caaadr'")
2171 (lambda (list val
) (setcar (cadar list
) val
))
2172 "`setf' inversion for `caadar'")
2175 (lambda (list val
) (setcar (cdaar list
) val
))
2176 "`setf' inversion for `cadaar'")
2179 (lambda (list val
) (setcdr (caar list
) val
))
2180 "`setf' inversion for `cdaaar'")
2183 (lambda (list val
) (setcar (caddr list
) val
))
2184 "`setf' inversion for `caaddr'")
2187 (lambda (list val
) (setcar (cdadr list
) val
))
2188 "`setf' inversion for `cadadr'")
2191 (lambda (list val
) (setcdr (caadr list
) val
))
2192 "`setf' inversion for `cdaadr'")
2195 (lambda (list val
) (setcar (cddar list
) val
))
2196 "`setf' inversion for `caddar'")
2199 (lambda (list val
) (setcdr (cadar list
) val
))
2200 "`setf' inversion for `cdadar'")
2203 (lambda (list val
) (setcdr (cdaar list
) val
))
2204 "`setf' inversion for `cddaar'")
2207 (lambda (list val
) (setcar (cdddr list
) val
))
2208 "`setf' inversion for `cadddr'")
2211 (lambda (list val
) (setcdr (cdadr list
) val
))
2212 "`setf' inversion for `cddadr'")
2215 (lambda (list val
) (setcdr (caddr list
) val
))
2216 "`setf' inversion for `cdaddr'")
2219 (lambda (list val
) (setcdr (cddar list
) val
))
2220 "`setf' inversion for `cdddar'")
2223 (lambda (list val
) (setcdr (cddr list
) val
))
2224 "`setf' inversion for `cddddr'")
2226 (defsetf get put
"`setf' inversion for `get' is `put'")
2228 (defsetf symbol-function fset
2229 "`setf' inversion for `symbol-function' is `fset'")
2231 (defsetf symbol-plist setplist
2232 "`setf' inversion for `symbol-plist' is `setplist'")
2234 (defsetf symbol-value set
2235 "`setf' inversion for `symbol-value' is `set'")
2237 (defsetf point goto-char
2238 "To set (point) to N, use (goto-char N)")
2240 ;; how about defsetfing other Emacs forms?
2244 ;;; It could be nice to implement define-modify-macro, but I don't
2245 ;;; think it really pays.
2247 (defmacro incf
(ref &optional delta
)
2248 "(incf REF [DELTA]) -> increment the g.v. REF by DELTA (default 1)"
2251 (list 'setf ref
(list '+ ref delta
)))
2253 (defmacro decf
(ref &optional delta
)
2254 "(decf REF [DELTA]) -> decrement the g.v. REF by DELTA (default 1)"
2257 (list 'setf ref
(list '- ref delta
)))
2259 (defmacro push
(item ref
)
2260 "(push ITEM REF) -> cons ITEM at the head of the g.v. REF (a list)"
2261 (list 'setf ref
(list 'cons item ref
)))
2263 (defmacro pushnew
(item ref
)
2264 "(pushnew ITEM REF): adjoin ITEM at the head of the g.v. REF (a list)"
2265 (list 'setf ref
(list 'adjoin item ref
)))
2268 "(pop REF) -> (prog1 (car REF) (setf REF (cdr REF)))"
2269 (let ((listname (gensym)))
2270 (list 'let
(list (list listname ref
))
2272 (list 'car listname
)
2273 (list 'setf ref
(list 'cdr listname
))))))
2277 ;;; Psetf is the generalized variable equivalent of psetq. The right
2278 ;;; hand sides are evaluated and assigned (via setf) to the left hand
2279 ;;; sides. The evaluations are done in an environment where they
2280 ;;; appear to occur in parallel.
2282 (defmacro psetf
(&rest body
)
2283 "(psetf {var value }...) => nil
2284 Like setf, but all the values are computed before any assignment is made."
2285 (let ((length (length body
)))
2286 (cond ((/= (% length
2) 0)
2287 (error "psetf needs an even number of arguments, %d given"
2294 (bodyforms (reverse body
)))
2296 (let* ((value (car bodyforms
))
2297 (place (cadr bodyforms
)))
2298 (setq bodyforms
(cddr bodyforms
))
2300 (setq setfs
(list 'setf place value
))
2301 (setq setfs
(list 'setf place
2306 ;;; SHIFTF and ROTATEF
2309 (defmacro shiftf
(&rest forms
)
2310 "(shiftf PLACE1 PLACE2... NEWVALUE)
2311 Set PLACE1 to PLACE2, PLACE2 to PLACE3...
2312 Each PLACE is set to the old value of the following PLACE,
2313 and the last PLACE is set to the value NEWVALUE.
2314 Returns the old value of PLACE1."
2315 (unless (> (length forms
) 1)
2316 (error "`shiftf' needs more than one argument"))
2317 (let ((places (butlast forms
))
2318 (newvalue (car (last forms
))))
2319 ;; the places are accessed to fresh symbols
2320 (multiple-value-bind
2322 (pair-with-newsyms places
)
2326 (append (cdr newsyms
) (list newvalue
))))
2329 (defmacro rotatef
(&rest places
)
2330 "(rotatef PLACE...) sets each PLACE to the old value of the following PLACE.
2331 The last PLACE is set to the old value of the first PLACE.
2332 Thus, the values rotate through the PLACEs. Returns nil."
2335 (multiple-value-bind
2337 (pair-with-newsyms places
)
2342 (append (cdr newsyms
) (list (car newsyms
)))))
2346 ;;;; This file provides the structures mechanism. See the
2347 ;;;; documentation for Common-Lisp's defstruct. Mine doesn't
2348 ;;;; implement all the functionality of the standard, although some
2349 ;;;; more could be grafted if so desired. More details along with
2353 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
2354 ;;;; (quiroz@cs.rochester.edu)
2357 (defkeyword :include
"Syntax of `defstruct'")
2358 (defkeyword :named
"Syntax of `defstruct'")
2359 (defkeyword :conc-name
"Syntax of `defstruct'")
2360 (defkeyword :copier
"Syntax of `defstruct'")
2361 (defkeyword :predicate
"Syntax of `defstruct'")
2362 (defkeyword :print-function
"Syntax of `defstruct'")
2363 (defkeyword :type
"Syntax of `defstruct'")
2364 (defkeyword :initial-offset
"Syntax of `defstruct'")
2366 (defkeyword :structure-doc
"Documentation string for a structure.")
2367 (defkeyword :structure-slotsn
"Number of slots in structure")
2368 (defkeyword :structure-slots
"List of the slot's names")
2369 (defkeyword :structure-indices
"List of (KEYWORD-NAME . INDEX)")
2370 (defkeyword :structure-initforms
"List of (KEYWORD-NAME . INITFORM)")
2371 (defkeyword :structure-includes
2372 "() or list of a symbol, that this struct includes")
2373 (defkeyword :structure-included-in
2374 "List of the structs that include this")
2377 (defmacro defstruct
(&rest args
)
2378 "(defstruct NAME [DOC-STRING] . SLOTS) define NAME as structure type.
2379 NAME must be a symbol, the name of the new structure. It could also
2380 be a list (NAME . OPTIONS).
2382 Each option is either a symbol, or a list of a keyword symbol taken from the
2383 list \{:conc-name, :copier, :constructor, :predicate, :include,
2384 :print-function, :type, :initial-offset\}. The meanings of these are as in
2385 CLtL, except that no BOA-constructors are provided, and the options
2386 \{:print-fuction, :type, :initial-offset\} are ignored quietly. All these
2387 structs are named, in the sense that their names can be used for type
2390 The DOC-STRING is established as the `structure-doc' property of NAME.
2392 The SLOTS are one or more of the following:
2393 SYMBOL -- meaning the SYMBOL is the name of a SLOT of NAME
2394 list of SYMBOL and VALUE -- meaning that VALUE is the initial value of
2396 `defstruct' defines functions `make-NAME', `NAME-p', `copy-NAME' for the
2397 structure, and functions with the same name as the slots to access
2398 them. `setf' of the accessors sets their values."
2399 (multiple-value-bind
2400 (name options docstring slotsn slots initlist
)
2401 (parse$defstruct$args args
)
2402 ;; Names for the member functions come from the options. The
2403 ;; slots* stuff collects info about the slots declared explicitly.
2404 (multiple-value-bind
2405 (conc-name constructor copier predicate
2406 moreslotsn moreslots moreinits included
)
2407 (parse$defstruct$options name options slots
)
2408 ;; The moreslots* stuff refers to slots gained as a consequence
2409 ;; of (:include clauses). -- Oct 89: Only one :include tolerated
2410 (when (and (numberp moreslotsn
)
2412 (setf slotsn
(+ slotsn moreslotsn
))
2413 (setf slots
(append moreslots slots
))
2414 (setf initlist
(append moreinits initlist
)))
2415 (unless (> slotsn
0)
2416 (error "%s needs at least one slot"
2417 (prin1-to-string name
)))
2418 (let ((dups (duplicate-symbols-p slots
)))
2420 (error "`%s' are duplicates"
2421 (prin1-to-string dups
))))
2422 (setq initlist
(simplify$inits slots initlist
))
2423 (let (properties functions keywords accessors alterators returned
)
2424 ;; compute properties of NAME
2428 (list 'put
(list 'quote name
) :structure-doc
2430 (list 'put
(list 'quote name
) :structure-slotsn
2432 (list 'put
(list 'quote name
) :structure-slots
2433 (list 'quote slots
))
2434 (list 'put
(list 'quote name
) :structure-initforms
2435 (list 'quote initlist
))
2436 (list 'put
(list 'quote name
) :structure-indices
2437 (list 'quote
(extract$indices initlist
))))
2438 ;; If this definition :includes another defstruct,
2439 ;; modify both property lists.
2445 (list 'quote included
))
2448 (list 'get
(list 'quote
(car included
))
2449 :structure-included-in
))))
2452 (let ((old (gensym)))
2458 :structure-includes
))))
2462 :structure-included-in
2465 ;; careful with destructive
2472 :structure-included-in
)
2479 ;; If this definition used to be :included in another, warn
2480 ;; that things make break. On the other hand, the redefinition
2481 ;; may be trivial, so don't call it an error.
2482 (let ((old (gensym)))
2485 (list (list old
(list 'get
2487 :structure-included-in
)))
2490 "`%s' redefined. Should redefine `%s'?"
2492 (list 'prin1-to-string old
))))))))
2494 ;; Compute functions associated with NAME. This is not
2495 ;; handling BOA constructors yet, but here would be the place.
2498 (list 'fset
(list 'quote constructor
)
2500 (list 'lambda
(list '&rest
'args
)
2501 (list 'make$structure$instance
2504 (list 'fset
(list 'quote copier
)
2506 (list 'lambda
(list 'struct
)
2507 (list 'copy-sequence
'struct
))))
2508 (let ((typetag (gensym)))
2509 (list 'fset
(list 'quote predicate
)
2513 'lambda
(list 'thing
)
2515 (list 'vectorp
'thing
)
2518 (list 'elt
'thing
0)))
2526 (list 'length
'thing
)
2533 :structure-included-in
))))))
2535 ;; compute accessors for NAME's slots
2536 (multiple-value-setq
2537 (accessors alterators keywords
)
2538 (build$accessors$for name conc-name predicate slots slotsn
))
2539 ;; generate returned value -- not defined by the standard
2544 '(lambda (x) (list 'quote x
))
2545 (cons name slots
)))))
2548 (nconc properties functions keywords
2549 accessors alterators returned
))))))
2551 (defun parse$defstruct$args
(args)
2552 "(parse$defstruct$args ARGS) => NAME OPTIONS DOCSTRING SLOTSN SLOTS INITLIST
2553 NAME=symbol, OPTIONS=list of, DOCSTRING=string, SLOTSN=count of slots,
2554 SLOTS=list of their names, INITLIST=alist (keyword . initform)."
2555 (let (name ;args=(symbol...) or ((symbol...)...)
2556 options
;args=((symbol . options) ...)
2557 (docstring "") ;args=(head docstring . slotargs)
2558 slotargs
;second or third cdr of args
2559 (slotsn 0) ;number of slots
2560 (slots '()) ;list of slot names
2561 (initlist '())) ;list of (slot keyword . initform)
2562 ;; extract name and options
2563 (cond ((symbolp (car args
)) ;simple name
2564 (setq name
(car args
)
2566 ((and (listp (car args
)) ;(name . options)
2567 (symbolp (caar args
)))
2568 (setq name
(caar args
)
2569 options
(cdar args
)))
2571 (error "first arg to `defstruct' must be symbol or (symbol ...)")))
2572 (setq slotargs
(cdr args
))
2573 ;; is there a docstring?
2574 (when (stringp (car slotargs
))
2575 (setq docstring
(car slotargs
)
2576 slotargs
(cdr slotargs
)))
2577 ;; now for the slots
2578 (multiple-value-bind
2579 (slotsn slots initlist
)
2580 (process$slots slotargs
)
2581 (values name options docstring slotsn slots initlist
))))
2583 (defun process$slots
(slots)
2584 "(process$slots SLOTS) => SLOTSN SLOTSLIST INITLIST
2585 Converts a list of symbols or lists of symbol and form into the last 3
2586 values returned by PARSE$DEFSTRUCT$ARGS."
2587 (let ((slotsn (length slots
)) ;number of slots
2588 slotslist
;(slot1 slot2 ...)
2589 initlist
) ;((:slot1 . init1) ...)
2591 ((ptr slots
(cdr ptr
))
2592 (this (car ptr
) (car ptr
)))
2594 (cond ((symbolp this
)
2595 (setq slotslist
(cons this slotslist
))
2596 (setq initlist
(acons (keyword-of this
) nil initlist
)))
2598 (symbolp (car this
)))
2599 (let ((name (car this
))
2601 ;; this silently ignores any slot options. bad...
2602 (setq slotslist
(cons name slotslist
))
2603 (setq initlist
(acons (keyword-of name
) form initlist
))))
2605 (error "slot should be symbol or (symbol ...), not `%s'"
2606 (prin1-to-string this
)))))
2607 (values slotsn
(nreverse slotslist
) (nreverse initlist
))))
2609 (defun parse$defstruct$options
(name options slots
)
2610 "(parse$defstruct$options name OPTIONS SLOTS) => many values
2611 A defstruct named NAME, with options list OPTIONS, has already slots SLOTS.
2612 Parse the OPTIONS and return the updated form of the struct's slots and other
2613 information. The values returned are:
2615 CONC-NAME is the string to use as prefix/suffix in the methods,
2616 CONST is the name of the official constructor,
2617 COPIER is the name of the structure copier,
2618 PRED is the name of the type predicate,
2619 MORESLOTSN is the number of slots added by :include,
2620 MORESLOTS is the list of slots added by :include,
2621 MOREINITS is the list of initialization forms added by :include,
2622 INCLUDED is nil, or the list of the symbol added by :include"
2623 (let* ((namestring (symbol-name name
))
2624 ;; to build the return values
2625 (conc-name (concat namestring
"-"))
2626 (const (intern (concat "make-" namestring
)))
2627 (copier (intern (concat "copy-" namestring
)))
2628 (pred (intern (concat namestring
"-p")))
2633 option-head
;When an option is not a plain
2634 option-second
; keyword, it must be a list of
2635 option-rest
; the form (head second . rest)
2636 these-slotsn
;When :include is found, the
2637 these-slots
; info about the included
2638 these-inits
; structure is added here.
2639 included
;NIL or (list INCLUDED)
2641 ;; Values above are the defaults. Now we read the options themselves
2642 (dolist (option options
)
2643 ;; 2 cases arise, as options must be a keyword or a list
2650 (error "can't recognize option `%s'"
2651 (prin1-to-string option
)))))
2652 ((and (listp option
)
2653 (keywordp (setq option-head
(car option
))))
2654 (setq option-second
(second option
))
2655 (setq option-rest
(nthcdr 2 option
))
2660 ((stringp option-second
)
2662 ((null option-second
)
2665 (error "`%s' is invalid as `conc-name'"
2666 (prin1-to-string option-second
))))))
2670 ((and (symbolp option-second
)
2674 (error "can't recognize option `%s'"
2675 (prin1-to-string option
))))))
2677 (:constructor
;no BOA-constructors allowed
2680 ((and (symbolp option-second
)
2684 (error "can't recognize option `%s'"
2685 (prin1-to-string option
))))))
2689 ((and (symbolp option-second
)
2693 (error "can't recognize option `%s'"
2694 (prin1-to-string option
))))))
2696 (unless (symbolp option-second
)
2697 (error "arg to `:include' should be a symbol, not `%s'"
2698 (prin1-to-string option-second
)))
2699 (setq these-slotsn
(get option-second
:structure-slotsn
)
2700 these-slots
(get option-second
:structure-slots
)
2701 these-inits
(get option-second
:structure-initforms
))
2702 (unless (and (numberp these-slotsn
)
2704 (error "`%s' is not a valid structure"
2705 (prin1-to-string option-second
)))
2707 (error "`%s' already includes `%s', can't include `%s' too"
2708 name
(car included
) option-second
)
2709 (push option-second included
))
2710 (multiple-value-bind
2711 (xtra-slotsn xtra-slots xtra-inits
)
2712 (process$slots option-rest
)
2713 (when (> xtra-slotsn
0)
2714 (dolist (xslot xtra-slots
)
2715 (unless (memq xslot these-slots
)
2716 (error "`%s' is not a slot of `%s'"
2717 (prin1-to-string xslot
)
2718 (prin1-to-string option-second
))))
2719 (setq these-inits
(append xtra-inits these-inits
)))
2720 (setq moreslotsn
(+ moreslotsn these-slotsn
))
2721 (setq moreslots
(append these-slots moreslots
))
2722 (setq moreinits
(append these-inits moreinits
))))
2723 ((:print-function
:type
:initial-offset
)
2726 (error "can't recognize option `%s'"
2727 (prin1-to-string option
)))))
2729 (error "can't recognize option `%s'"
2730 (prin1-to-string option
)))))
2731 ;; Return values found
2732 (values conc-name const copier pred
2733 moreslotsn moreslots moreinits
2736 (defun simplify$inits
(slots initlist
)
2737 "(simplify$inits SLOTS INITLIST) => new INITLIST
2738 Removes from INITLIST - an ALIST - any shadowed bindings."
2739 (let ((result '()) ;built here
2742 (dolist (slot slots
)
2743 (setq key
(keyword-of slot
))
2744 (setq result
(acons key
(cdr (assoc key initlist
)) result
)))
2747 (defun extract$indices
(initlist)
2748 "(extract$indices INITLIST) => indices list
2749 Kludge. From a list of pairs (keyword . form) build a list of pairs
2750 of the form (keyword . position in list from 0). Useful to precompute
2751 some of the work of MAKE$STRUCTURE$INSTANCE."
2754 (dolist (entry initlist
(nreverse result
))
2755 (setq result
(acons (car entry
) index result
)
2756 index
(+ index
1)))))
2758 (defun build$accessors$for
(name conc-name predicate slots slotsn
)
2759 "(build$accessors$for NAME PREDICATE SLOTS SLOTSN) => FSETS DEFSETFS KWDS
2760 Generate the code for accesors and defsetfs of a structure called
2761 NAME, whose slots are SLOTS. Also, establishes the keywords for the
2767 (canonic "")) ;slot name with conc-name prepended
2770 (nreverse accessors
) (nreverse alterators
) (nreverse keywords
)))
2771 (setq canonic
(intern (concat conc-name
(symbol-name (nth i slots
)))))
2774 (list 'fset
(list 'quote canonic
)
2776 (list 'lambda
(list 'object
)
2778 (list (list predicate
'object
)
2779 (list 'aref
'object
(1+ i
)))
2782 "`%s' is not a struct %s"
2783 (list 'prin1-to-string
2785 (list 'prin1-to-string
2791 (list 'defsetf canonic
2792 (list 'lambda
(list 'object
'newval
)
2794 (list (list predicate
'object
)
2795 (list 'aset
'object
(1+ i
) 'newval
))
2799 (list 'prin1-to-string
2801 (list 'prin1-to-string
2806 (cons (list 'defkeyword
(keyword-of (nth i slots
)))
2809 (defun make$structure$instance
(name args
)
2810 "(make$structure$instance NAME ARGS) => new struct NAME
2811 A struct of type NAME is created, some slots might be initialized
2812 according to ARGS (the &rest argument of MAKE-name)."
2813 (unless (symbolp name
)
2814 (error "`%s' is not a possible name for a structure"
2815 (prin1-to-string name
)))
2816 (let ((initforms (get name
:structure-initforms
))
2817 (slotsn (get name
:structure-slotsn
))
2818 (indices (get name
:structure-indices
))
2819 initalist
;pairlis'd on initforms
2820 initializers
;definitive initializers
2822 ;; check sanity of the request
2823 (unless (and (numberp slotsn
)
2825 (error "`%s' is not a defined structure"
2826 (prin1-to-string name
)))
2827 (unless (evenp (length args
))
2828 (error "slot initializers `%s' not of even length"
2829 (prin1-to-string args
)))
2830 ;; analyze the initializers provided by the call
2831 (multiple-value-bind
2832 (speckwds specvals
) ;keywords and values given
2833 (unzip-list args
) ; by the user
2834 ;; check that all the arguments are introduced by keywords
2835 (unless (every (function keywordp
) speckwds
)
2836 (error "all of the names in `%s' should be keywords"
2837 (prin1-to-string speckwds
)))
2838 ;; check that all the keywords are known
2839 (dolist (kwd speckwds
)
2840 (unless (numberp (cdr (assoc kwd indices
)))
2841 (error "`%s' is not a valid slot name for %s"
2842 (prin1-to-string kwd
) (prin1-to-string name
))))
2846 (do* ;;protect values from further evaluation
2847 ((ptr specvals
(cdr ptr
))
2848 (val (car ptr
) (car ptr
))
2850 ((endp ptr
) (nreverse result
))
2852 (cons (list 'quote val
)
2854 (copy-sequence initforms
)))
2855 ;; compute definitive initializers
2857 (do* ;;gather the values of the most definitive forms
2858 ((ptr indices
(cdr ptr
))
2859 (key (caar ptr
) (caar ptr
))
2861 ((endp ptr
) (nreverse result
))
2863 (cons (eval (cdr (assoc key initalist
))) result
))))
2864 ;; do real initialization
2865 (apply (function vector
)
2866 (cons name initializers
)))))
2868 ;;;; end of cl-structs.el
2870 ;;; For lisp-interaction mode, so that multiple values can be seen when passed
2871 ;;; back. Lies every now and then...
2873 (defvar - nil
"form currently under evaluation")
2874 (defvar + nil
"previous -")
2875 (defvar ++ nil
"previous +")
2876 (defvar +++ nil
"previous ++")
2877 (defvar / nil
"list of values returned by +")
2878 (defvar // nil
"list of values returned by ++")
2879 (defvar /// nil
"list of values returned by +++")
2880 (defvar * nil
"(first) value of +")
2881 (defvar ** nil
"(first) value of ++")
2882 (defvar *** nil
"(first) value of +++")
2884 (defun cl-eval-print-last-sexp ()
2885 "Evaluate sexp before point; print value\(s\) into current buffer.
2886 If the evaled form returns multiple values, they are shown one to a line.
2887 The variables -, +, ++, +++, *, **, ***, /, //, /// have their usual meaning.
2889 It clears the multiple-value passing mechanism, and does not pass back
2890 multiple values. Use this only if you are debugging cl.el and understand well
2891 how the multiple-value stuff works, because it can be fooled into believing
2892 that multiple values have been returned when they actually haven't, for
2894 \(identity \(values nil 1\)\)
2895 However, even when this fails, you can trust the first printed value to be
2896 \(one of\) the returned value\(s\)."
2898 ;; top level call, can reset mvalues
2899 (setq *mvalues-count
* nil
2900 *mvalues-values
* nil
)
2901 (setq -
(car (read-from-string
2903 (let ((stab (syntax-table)))
2906 (set-syntax-table emacs-lisp-mode-syntax-table
)
2909 (set-syntax-table stab
)))
2920 (cond ((or (null *mvalues-count
*) ;mvalues mechanism not used
2921 (not (eq * (car *mvalues-values
*))))
2922 (print * (current-buffer)))
2923 ((null /) ;no values returned
2924 (terpri (current-buffer)))
2925 (t ;more than zero mvalues
2926 (terpri (current-buffer))
2927 (mapcar (function (lambda (value)
2928 (prin1 value
(current-buffer))
2929 (terpri (current-buffer))))
2931 (setq *mvalues-count
* nil
;make sure
2932 *mvalues-values
* nil
))
2934 ;;;; More LISTS functions
2937 ;;; Some mapping functions on lists, commonly useful.
2938 ;;; They take no extra sequences, to go along with Emacs Lisp's MAPCAR.
2940 (defun mapc (function list
)
2941 "(MAPC FUNCTION LIST) => LIST
2942 Apply FUNCTION to each element of LIST, return LIST.
2943 Like mapcar, but called only for effect."
2946 (funcall function
(car args
))
2947 (setq args
(cdr args
))))
2950 (defun maplist (function list
)
2951 "(MAPLIST FUNCTION LIST) => list'ed results of FUNCTION on cdrs of LIST
2952 Apply FUNCTION to successive sublists of LIST, return the list of the results"
2956 (setq results
(cons (funcall function args
) results
)
2958 (nreverse results
)))
2960 (defun mapl (function list
)
2961 "(MAPL FUNCTION LIST) => LIST
2962 Apply FUNCTION to successive cdrs of LIST, return LIST.
2963 Like maplist, but called only for effect."
2966 (funcall function args
)
2967 (setq args
(cdr args
)))
2970 (defun mapcan (function list
)
2971 "(MAPCAN FUNCTION LIST) => nconc'd results of FUNCTION on LIST
2972 Apply FUNCTION to each element of LIST, nconc the results.
2973 Beware: nconc destroys its first argument! See copy-list."
2977 (setq results
(nconc (funcall function
(car args
)) results
)
2979 (nreverse results
)))
2981 (defun mapcon (function list
)
2982 "(MAPCON FUNCTION LIST) => nconc'd results of FUNCTION on cdrs of LIST
2983 Apply FUNCTION to successive sublists of LIST, nconc the results.
2984 Beware: nconc destroys its first argument! See copy-list."
2988 (setq results
(nconc (funcall function args
) results
)
2990 (nreverse results
)))
2994 (defun copy-list (list)
2995 "Build a copy of LIST"
2998 (defun copy-tree (tree)
2999 "Build a copy of the tree of conses TREE
3000 The argument is a tree of conses, it is recursively copied down to
3001 non conses. Circularity and sharing of substructure are not
3002 necessarily preserved."
3004 (cons (copy-tree (car tree
))
3005 (copy-tree (cdr tree
)))
3008 ;;; reversals, and destructive manipulations of a list's spine
3010 (defun revappend (x y
)
3011 "does what (append (reverse X) Y) would, only faster"
3014 (revappend (cdr x
) (cons (car x
) y
))))
3016 (defun nreconc (x y
)
3017 "does (nconc (nreverse X) Y) would, only faster
3018 Destructive on X, be careful."
3021 ;; reuse the first cons of x, making it point to y
3022 (nreconc (cdr x
) (prog1 x
(rplacd x y
)))))
3024 (defun nbutlast (list &optional n
)
3025 "Side-effected LIST truncated N+1 conses from the end.
3026 This is the destructive version of BUTLAST. Returns () and does not
3027 modify the LIST argument if the length of the list is not at least N."
3028 (when (null n
) (setf n
1))
3029 (let ((length (list-length list
)))
3030 (cond ((null length
)
3035 (setnthcdr (- length n
) list nil
)
3040 (defun subst (new old tree
)
3041 "NEW replaces OLD in a copy of TREE
3042 Uses eql for the test."
3043 (subst-if new
(function (lambda (x) (eql x old
))) tree
))
3045 (defun subst-if-not (new test tree
)
3046 "NEW replaces any subtree or leaf that fails TEST in a copy of TREE"
3047 ;; (subst-if new (function (lambda (x) (not (funcall test x)))) tree)
3048 (cond ((not (funcall test tree
))
3053 (let ((head (subst-if-not new test
(car tree
)))
3054 (tail (subst-if-not new test
(cdr tree
))))
3055 ;; If nothing changed, return originals. Else use the new
3056 ;; components to assemble a new tree.
3057 (if (and (eql head
(car tree
))
3058 (eql tail
(cdr tree
)))
3060 (cons head tail
))))))
3062 (defun subst-if (new test tree
)
3063 "NEW replaces any subtree or leaf that satisfies TEST in a copy of TREE"
3064 (cond ((funcall test tree
)
3069 (let ((head (subst-if new test
(car tree
)))
3070 (tail (subst-if new test
(cdr tree
))))
3071 ;; If nothing changed, return originals. Else use the new
3072 ;; components to assemble a new tree.
3073 (if (and (eql head
(car tree
))
3074 (eql tail
(cdr tree
)))
3076 (cons head tail
))))))
3078 (defun sublis (alist tree
)
3079 "Use association list ALIST to modify a copy of TREE
3080 If a subtree or leaf of TREE is a key in ALIST, it is replaced by the
3081 associated value. Not exactly Common Lisp, but close in spirit and
3082 compatible with the native Emacs Lisp ASSOC, which uses EQUAL."
3083 (let ((toplevel (assoc tree alist
)))
3084 (cond (toplevel ;Bingo at top
3086 ((atom tree
) ;Give up on this
3089 (let ((head (sublis alist
(car tree
)))
3090 (tail (sublis alist
(cdr tree
))))
3091 (if (and (eql head
(car tree
))
3092 (eql tail
(cdr tree
)))
3094 (cons head tail
)))))))
3096 (defun member-if (predicate list
)
3097 "PREDICATE is applied to the members of LIST. As soon as one of them
3098 returns true, that tail of the list if returned. Else NIL."
3099 (catch 'found-member-if
3100 (while (not (endp list
))
3101 (if (funcall predicate
(car list
))
3102 (throw 'found-member-if list
)
3103 (setq list
(cdr list
))))
3106 (defun member-if-not (predicate list
)
3107 "PREDICATE is applied to the members of LIST. As soon as one of them
3108 returns false, that tail of the list if returned. Else NIL."
3109 (catch 'found-member-if-not
3110 (while (not (endp list
))
3111 (if (funcall predicate
(car list
))
3112 (setq list
(cdr list
))
3113 (throw 'found-member-if-not list
)))
3116 (defun tailp (sublist list
)
3117 "(tailp SUBLIST LIST) => True if SUBLIST is a sublist of LIST."
3119 (while (not (endp list
))
3120 (if (eq sublist list
)
3121 (throw 'tailp-found t
)
3122 (setq list
(cdr list
))))
3125 ;;; Suggestion of phr%widow.Berkeley.EDU@lilac.berkeley.edu
3127 (defmacro declare
(&rest decls
)
3128 "Ignore a Common-Lisp declaration."
3129 "declarations are ignored in this implementation")
3131 (defun proclaim (&rest decls
)
3132 "Ignore a Common-Lisp proclamation."
3133 "declarations are ignored in this implementation")
3135 (defmacro the
(type form
)
3136 "(the TYPE FORM) macroexpands to FORM
3137 No checking is even attempted. This is just for compatibility with