XEmacs 21.2-b1
[chise/xemacs-chise.git.1] / lisp / cl-macs.el
1 ;;; cl-macs.el --- Common Lisp extensions for GNU Emacs Lisp (part four)
2
3 ;; Copyright (C) 1993 Free Software Foundation, Inc.
4
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Version: 2.02
7 ;; Keywords: extensions
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: FSF 19.34.
27
28 ;;; Commentary:
29
30 ;; These are extensions to Emacs Lisp that provide a degree of
31 ;; Common Lisp compatibility, beyond what is already built-in
32 ;; in Emacs Lisp.
33 ;;
34 ;; This package was written by Dave Gillespie; it is a complete
35 ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
36 ;;
37 ;; This package works with Emacs 18, Emacs 19, and Lucid Emacs 19.
38 ;;
39 ;; Bug reports, comments, and suggestions are welcome!
40
41 ;; This file contains the portions of the Common Lisp extensions
42 ;; package which should be autoloaded, but need only be present
43 ;; if the compiler or interpreter is used---this file is not
44 ;; necessary for executing compiled code.
45
46 ;; See cl.el for Change Log.
47
48
49 ;;; Code:
50
51 (or (memq 'cl-19 features)
52     (error "Tried to load `cl-macs' before `cl'!"))
53
54
55 ;;; We define these here so that this file can compile without having
56 ;;; loaded the cl.el file already.
57
58 (defmacro cl-push (x place) (list 'setq place (list 'cons x place)))
59 (defmacro cl-pop (place)
60   (list 'car (list 'prog1 place (list 'setq place (list 'cdr place)))))
61 (defmacro cl-pop2 (place)
62   (list 'prog1 (list 'car (list 'cdr place))
63         (list 'setq place (list 'cdr (list 'cdr place)))))
64 (put 'cl-push 'edebug-form-spec 'edebug-sexps)
65 (put 'cl-pop 'edebug-form-spec 'edebug-sexps)
66 (put 'cl-pop2 'edebug-form-spec 'edebug-sexps)
67
68 (defvar cl-emacs-type)
69 (defvar cl-optimize-safety)
70 (defvar cl-optimize-speed)
71
72
73 ;;; This kludge allows macros which use cl-transform-function-property
74 ;;; to be called at compile-time.
75
76 (require
77  (progn
78    (or (fboundp 'defalias) (fset 'defalias 'fset))
79    (or (fboundp 'cl-transform-function-property)
80        (defalias 'cl-transform-function-property
81          (function (lambda (n p f)
82                      (list 'put (list 'quote n) (list 'quote p)
83                            (list 'function (cons 'lambda f)))))))
84    (car (or features (setq features (list 'cl-kludge))))))
85
86
87 ;;; Initialization.
88
89 (defvar cl-old-bc-file-form nil)
90
91 ;; Patch broken Emacs 18 compiler (re top-level macros).
92 ;; Emacs 19 compiler doesn't need this patch.
93 ;; Also, undo broken definition of `eql' that uses same bytecode as `eq'.
94
95 ;;;###autoload
96 (defun cl-compile-time-init ()
97   (setq cl-old-bc-file-form (symbol-function 'byte-compile-file-form))
98   (or (fboundp 'byte-compile-flush-pending)   ; Emacs 19 compiler?
99       (defalias 'byte-compile-file-form
100         (function
101          (lambda (form)
102            (setq form (macroexpand form byte-compile-macro-environment))
103            (if (eq (car-safe form) 'progn)
104                (cons 'progn (mapcar 'byte-compile-file-form (cdr form)))
105              (funcall cl-old-bc-file-form form))))))
106   (put 'eql 'byte-compile 'cl-byte-compile-compiler-macro)
107   (run-hooks 'cl-hack-bytecomp-hook))
108
109
110 ;;; Symbols.
111
112 (defvar *gensym-counter*)
113
114 ;;;###autoload
115 (defun gensym (&optional arg)
116   "Generate a new uninterned symbol.
117 The name is made by appending a number to PREFIX, default \"G\"."
118   (let ((prefix (if (stringp arg) arg "G"))
119         (num (if (integerp arg) arg
120                (prog1 *gensym-counter*
121                  (setq *gensym-counter* (1+ *gensym-counter*))))))
122     (make-symbol (format "%s%d" prefix num))))
123
124 ;;;###autoload
125 (defun gentemp (&optional arg)
126   "Generate a new interned symbol with a unique name.
127 The name is made by appending a number to PREFIX, default \"G\"."
128   (let ((prefix (if (stringp arg) arg "G"))
129         name)
130     (while (intern-soft (setq name (format "%s%d" prefix *gensym-counter*)))
131       (setq *gensym-counter* (1+ *gensym-counter*)))
132     (intern name)))
133
134
135 ;;; Program structure.
136
137 ;;;###autoload
138 (defmacro defun* (name args &rest body)
139   "(defun* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
140 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
141 and BODY is implicitly surrounded by (block NAME ...)."
142   (let* ((res (cl-transform-lambda (cons args body) name))
143          (form (list* 'defun name (cdr res))))
144     (if (car res) (list 'progn (car res) form) form)))
145
146 ;;;###autoload
147 (defmacro defmacro* (name args &rest body)
148   "(defmacro* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a macro.
149 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
150 and BODY is implicitly surrounded by (block NAME ...)."
151   (let* ((res (cl-transform-lambda (cons args body) name))
152          (form (list* 'defmacro name (cdr res))))
153     (if (car res) (list 'progn (car res) form) form)))
154
155 ;;;###autoload
156 (defmacro function* (func)
157   "(function* SYMBOL-OR-LAMBDA): introduce a function.
158 Like normal `function', except that if argument is a lambda form, its
159 ARGLIST allows full Common Lisp conventions."
160   (if (eq (car-safe func) 'lambda)
161       (let* ((res (cl-transform-lambda (cdr func) 'cl-none))
162              (form (list 'function (cons 'lambda (cdr res)))))
163         (if (car res) (list 'progn (car res) form) form))
164     (list 'function func)))
165
166 (defun cl-transform-function-property (func prop form)
167   (let ((res (cl-transform-lambda form func)))
168     (append '(progn) (cdr (cdr (car res)))
169             (list (list 'put (list 'quote func) (list 'quote prop)
170                         (list 'function (cons 'lambda (cdr res))))))))
171
172 (defconst lambda-list-keywords
173   '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
174
175 (defvar cl-macro-environment nil)
176 (defvar bind-block) (defvar bind-defs) (defvar bind-enquote)
177 (defvar bind-inits) (defvar bind-lets) (defvar bind-forms)
178
179 (defun cl-transform-lambda (form bind-block)
180   (let* ((args (car form)) (body (cdr form))
181          (bind-defs nil) (bind-enquote nil)
182          (bind-inits nil) (bind-lets nil) (bind-forms nil)
183          (header nil) (simple-args nil))
184     (while (or (stringp (car body)) (eq (car-safe (car body)) 'interactive))
185       (cl-push (cl-pop body) header))
186     (setq args (if (listp args) (copy-list args) (list '&rest args)))
187     (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
188     (if (setq bind-defs (cadr (memq '&cl-defs args)))
189         (setq args (delq '&cl-defs (delq bind-defs args))
190               bind-defs (cadr bind-defs)))
191     (if (setq bind-enquote (memq '&cl-quote args))
192         (setq args (delq '&cl-quote args)))
193     (if (memq '&whole args) (error "&whole not currently implemented"))
194     (let* ((p (memq '&environment args)) (v (cadr p)))
195       (if p (setq args (nconc (delq (car p) (delq v args))
196                               (list '&aux (list v 'cl-macro-environment))))))
197     (while (and args (symbolp (car args))
198                 (not (memq (car args) '(nil &rest &body &key &aux)))
199                 (not (and (eq (car args) '&optional)
200                           (or bind-defs (consp (cadr args))))))
201       (cl-push (cl-pop args) simple-args))
202     (or (eq bind-block 'cl-none)
203         (setq body (list (list* 'block bind-block body))))
204     (if (null args)
205         (list* nil (nreverse simple-args) (nconc (nreverse header) body))
206       (if (memq '&optional simple-args) (cl-push '&optional args))
207       (cl-do-arglist args nil (- (length simple-args)
208                                  (if (memq '&optional simple-args) 1 0)))
209       (setq bind-lets (nreverse bind-lets))
210       (list* (and bind-inits (list* 'eval-when '(compile load eval)
211                                     (nreverse bind-inits)))
212              (nconc (nreverse simple-args)
213                     (list '&rest (car (cl-pop bind-lets))))
214              (nconc (nreverse header)
215                     (list (nconc (list 'let* bind-lets)
216                                  (nreverse bind-forms) body)))))))
217
218 (defun cl-do-arglist (args expr &optional num)   ; uses bind-*
219   (if (nlistp args)
220       (if (or (memq args lambda-list-keywords) (not (symbolp args)))
221           (error "Invalid argument name: %s" args)
222         (cl-push (list args expr) bind-lets))
223     (setq args (copy-list args))
224     (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
225     (let ((p (memq '&body args))) (if p (setcar p '&rest)))
226     (if (memq '&environment args) (error "&environment used incorrectly"))
227     (let ((save-args args)
228           (restarg (memq '&rest args))
229           (safety (if (cl-compiling-file) cl-optimize-safety 3))
230           (keys nil)
231           (laterarg nil) (exactarg nil) minarg)
232       (or num (setq num 0))
233       (if (listp (cadr restarg))
234           (setq restarg (gensym "--rest--"))
235         (setq restarg (cadr restarg)))
236       (cl-push (list restarg expr) bind-lets)
237       (if (eq (car args) '&whole)
238           (cl-push (list (cl-pop2 args) restarg) bind-lets))
239       (let ((p args))
240         (setq minarg restarg)
241         (while (and p (not (memq (car p) lambda-list-keywords)))
242           (or (eq p args) (setq minarg (list 'cdr minarg)))
243           (setq p (cdr p)))
244         (if (memq (car p) '(nil &aux))
245             (setq minarg (list '= (list 'length restarg)
246                                (length (ldiff args p)))
247                   exactarg (not (eq args p)))))
248       (while (and args (not (memq (car args) lambda-list-keywords)))
249         (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
250                             restarg)))
251           (cl-do-arglist
252            (cl-pop args)
253            (if (or laterarg (= safety 0)) poparg
254              (list 'if minarg poparg
255                    (list 'signal '(quote wrong-number-of-arguments)
256                          (list 'list (and (not (eq bind-block 'cl-none))
257                                           (list 'quote bind-block))
258                                (list 'length restarg)))))))
259         (setq num (1+ num) laterarg t))
260       (while (and (eq (car args) '&optional) (cl-pop args))
261         (while (and args (not (memq (car args) lambda-list-keywords)))
262           (let ((arg (cl-pop args)))
263             (or (consp arg) (setq arg (list arg)))
264             (if (cddr arg) (cl-do-arglist (nth 2 arg) (list 'and restarg t)))
265             (let ((def (if (cdr arg) (nth 1 arg)
266                          (or (car bind-defs)
267                              (nth 1 (assq (car arg) bind-defs)))))
268                   (poparg (list 'pop restarg)))
269               (and def bind-enquote (setq def (list 'quote def)))
270               (cl-do-arglist (car arg)
271                              (if def (list 'if restarg poparg def) poparg))
272               (setq num (1+ num))))))
273       (if (eq (car args) '&rest)
274           (let ((arg (cl-pop2 args)))
275             (if (consp arg) (cl-do-arglist arg restarg)))
276         (or (eq (car args) '&key) (= safety 0) exactarg
277             (cl-push (list 'if restarg
278                            (list 'signal '(quote wrong-number-of-arguments)
279                                  (list 'list
280                                        (and (not (eq bind-block 'cl-none))
281                                             (list 'quote bind-block))
282                                        (list '+ num (list 'length restarg)))))
283                      bind-forms)))
284       (while (and (eq (car args) '&key) (cl-pop args))
285         (while (and args (not (memq (car args) lambda-list-keywords)))
286           (let ((arg (cl-pop args)))
287             (or (consp arg) (setq arg (list arg)))
288             (let* ((karg (if (consp (car arg)) (caar arg)
289                            (intern (format ":%s" (car arg)))))
290                    (varg (if (consp (car arg)) (cadar arg) (car arg)))
291                    (def (if (cdr arg) (cadr arg)
292                           (or (car bind-defs) (cadr (assq varg bind-defs)))))
293                    (look (list 'memq (list 'quote karg) restarg)))
294               (and def bind-enquote (setq def (list 'quote def)))
295               (if (cddr arg)
296                   (let* ((temp (or (nth 2 arg) (gensym)))
297                          (val (list 'car (list 'cdr temp))))
298                     (cl-do-arglist temp look)
299                     (cl-do-arglist varg
300                                    (list 'if temp
301                                          (list 'prog1 val (list 'setq temp t))
302                                          def)))
303                 (cl-do-arglist
304                  varg
305                  (list 'car
306                        (list 'cdr
307                              (if (null def)
308                                  look
309                                (list 'or look
310                                      (if (eq (cl-const-expr-p def) t)
311                                          (list
312                                           'quote
313                                           (list nil (cl-const-expr-val def)))
314                                        (list 'list nil def))))))))
315               (cl-push karg keys)
316               (if (= (aref (symbol-name karg) 0) ?:)
317                   (progn (set karg karg)
318                          (cl-push (list 'setq karg (list 'quote karg))
319                                   bind-inits)))))))
320       (setq keys (nreverse keys))
321       (or (and (eq (car args) '&allow-other-keys) (cl-pop args))
322           (null keys) (= safety 0)
323           (let* ((var (gensym "--keys--"))
324                  (allow '(:allow-other-keys))
325                  (check (list
326                          'while var
327                          (list
328                           'cond
329                           (list (list 'memq (list 'car var)
330                                       (list 'quote (append keys allow)))
331                                 (list 'setq var (list 'cdr (list 'cdr var))))
332                           (list (list 'car
333                                       (list 'cdr
334                                             (list 'memq (cons 'quote allow)
335                                                   restarg)))
336                                 (list 'setq var nil))
337                           (list t
338                                 (list
339                                  'error
340                                  (format "Keyword argument %%s not one of %s"
341                                          keys)
342                                  (list 'car var)))))))
343             (cl-push (list 'let (list (list var restarg)) check) bind-forms)))
344       (while (and (eq (car args) '&aux) (cl-pop args))
345         (while (and args (not (memq (car args) lambda-list-keywords)))
346           (if (consp (car args))
347               (if (and bind-enquote (cadar args))
348                   (cl-do-arglist (caar args)
349                                  (list 'quote (cadr (cl-pop args))))
350                 (cl-do-arglist (caar args) (cadr (cl-pop args))))
351             (cl-do-arglist (cl-pop args) nil))))
352       (if args (error "Malformed argument list %s" save-args)))))
353
354 (defun cl-arglist-args (args)
355   (if (nlistp args) (list args)
356     (let ((res nil) (kind nil) arg)
357       (while (consp args)
358         (setq arg (cl-pop args))
359         (if (memq arg lambda-list-keywords) (setq kind arg)
360           (if (eq arg '&cl-defs) (cl-pop args)
361             (and (consp arg) kind (setq arg (car arg)))
362             (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
363             (setq res (nconc res (cl-arglist-args arg))))))
364       (nconc res (and args (list args))))))
365
366 ;;;###autoload
367 (defmacro destructuring-bind (args expr &rest body)
368   (let* ((bind-lets nil) (bind-forms nil) (bind-inits nil)
369          (bind-defs nil) (bind-block 'cl-none))
370     (cl-do-arglist (or args '(&aux)) expr)
371     (append '(progn) bind-inits
372             (list (nconc (list 'let* (nreverse bind-lets))
373                          (nreverse bind-forms) body)))))
374
375
376 ;;; The `eval-when' form.
377
378 (defvar cl-not-toplevel nil)
379
380 ;;;###autoload
381 (defmacro eval-when (when &rest body)
382   "(eval-when (WHEN...) BODY...): control when BODY is evaluated.
383 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
384 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
385 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level."
386   (if (and (fboundp 'cl-compiling-file) (cl-compiling-file)
387            (not cl-not-toplevel) (not (boundp 'for-effect)))  ; horrible kludge
388       (let ((comp (or (memq 'compile when) (memq ':compile-toplevel when)))
389             (cl-not-toplevel t))
390         (if (or (memq 'load when) (memq ':load-toplevel when))
391             (if comp (cons 'progn (mapcar 'cl-compile-time-too body))
392               (list* 'if nil nil body))
393           (progn (if comp (eval (cons 'progn body))) nil)))
394     (and (or (memq 'eval when) (memq ':execute when))
395          (cons 'progn body))))
396
397 (defun cl-compile-time-too (form)
398   (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
399       (setq form (macroexpand
400                   form (cons '(eval-when) byte-compile-macro-environment))))
401   (cond ((eq (car-safe form) 'progn)
402          (cons 'progn (mapcar 'cl-compile-time-too (cdr form))))
403         ((eq (car-safe form) 'eval-when)
404          (let ((when (nth 1 form)))
405            (if (or (memq 'eval when) (memq ':execute when))
406                (list* 'eval-when (cons 'compile when) (cddr form))
407              form)))
408         (t (eval form) form)))
409
410 (or (and (fboundp 'eval-when-compile)
411          (not (eq (car-safe (symbol-function 'eval-when-compile)) 'autoload)))
412     (eval '(defmacro eval-when-compile (&rest body)
413              "Like `progn', but evaluates the body at compile time.
414 The result of the body appears to the compiler as a quoted constant."
415              (list 'quote (eval (cons 'progn body))))))
416
417 ;;;###autoload
418 (defmacro load-time-value (form &optional read-only)
419   "Like `progn', but evaluates the body at load time.
420 The result of the body appears to the compiler as a quoted constant."
421   (if (cl-compiling-file)
422       (let* ((temp (gentemp "--cl-load-time--"))
423              (set (list 'set (list 'quote temp) form)))
424         (if (and (fboundp 'byte-compile-file-form-defmumble)
425                  (boundp 'this-kind) (boundp 'that-one))
426             (fset 'byte-compile-file-form
427                   (list 'lambda '(form)
428                         (list 'fset '(quote byte-compile-file-form)
429                               (list 'quote
430                                     (symbol-function 'byte-compile-file-form)))
431                         (list 'byte-compile-file-form (list 'quote set))
432                         '(byte-compile-file-form form)))
433           ;; XEmacs change
434           (print set (symbol-value ;;'outbuffer
435                                    'byte-compile-output-buffer
436                                    )))
437         (list 'symbol-value (list 'quote temp)))
438     (list 'quote (eval form))))
439
440
441 ;;; Conditional control structures.
442
443 ;;;###autoload
444 (defmacro case (expr &rest clauses)
445   "(case EXPR CLAUSES...): evals EXPR, chooses from CLAUSES on that value.
446 Each clause looks like (KEYLIST BODY...).  EXPR is evaluated and compared
447 against each key in each KEYLIST; the corresponding BODY is evaluated.
448 If no clause succeeds, case returns nil.  A single atom may be used in
449 place of a KEYLIST of one atom.  A KEYLIST of `t' or `otherwise' is
450 allowed only in the final clause, and matches if no other keys match.
451 Key values are compared by `eql'."
452   (let* ((temp (if (cl-simple-expr-p expr 3) expr (gensym)))
453          (head-list nil)
454          (last-clause (car (last clauses)))
455          (body (cons
456                 'cond
457                 (mapcar
458                  (function
459                   (lambda (c)
460                     (cons (cond ((memq (car c) '(t otherwise))
461                                  (or (eq c last-clause)
462                                      (error
463                                       "`%s' is allowed only as the last case clause"
464                                       (car c)))
465                                  t)
466                                 ((eq (car c) 'ecase-error-flag)
467                                  (list 'error "ecase failed: %s, %s"
468                                        temp (list 'quote (reverse head-list))))
469                                 ((listp (car c))
470                                  (setq head-list (append (car c) head-list))
471                                  (list 'member* temp (list 'quote (car c))))
472                                 (t
473                                  (if (memq (car c) head-list)
474                                      (error "Duplicate key in case: %s"
475                                             (car c)))
476                                  (cl-push (car c) head-list)
477                                  (list 'eql temp (list 'quote (car c)))))
478                           (or (cdr c) '(nil)))))
479                  clauses))))
480     (if (eq temp expr) body
481       (list 'let (list (list temp expr)) body))))
482
483 ;; #### CL standard also requires `ccase', which signals a continuable
484 ;; error (`cerror' in XEmacs).  However, I don't think it buys us
485 ;; anything to introduce it, as there is probably much more CL stuff
486 ;; missing, and the feature is not essential.  --hniksic
487
488 ;;;###autoload
489 (defmacro ecase (expr &rest clauses)
490   "(ecase EXPR CLAUSES...): like `case', but error if no case fits.
491 `otherwise'-clauses are not allowed."
492   (let ((disallowed (or (assq t clauses)
493                         (assq 'otherwise clauses))))
494     (if disallowed
495         (error "`%s' is not allowed in ecase" (car disallowed))))
496   (list* 'case expr (append clauses '((ecase-error-flag)))))
497
498 ;;;###autoload
499 (defmacro typecase (expr &rest clauses)
500   "(typecase EXPR CLAUSES...): evals EXPR, chooses from CLAUSES on that value.
501 Each clause looks like (TYPE BODY...).  EXPR is evaluated and, if it
502 satisfies TYPE, the corresponding BODY is evaluated.  If no clause succeeds,
503 typecase returns nil.  A TYPE of `t' or `otherwise' is allowed only in the
504 final clause, and matches if no other keys match."
505   (let* ((temp (if (cl-simple-expr-p expr 3) expr (gensym)))
506          (type-list nil)
507          (body (cons
508                 'cond
509                 (mapcar
510                  (function
511                   (lambda (c)
512                     (cons (cond ((eq (car c) 'otherwise) t)
513                                 ((eq (car c) 'ecase-error-flag)
514                                  (list 'error "etypecase failed: %s, %s"
515                                        temp (list 'quote (reverse type-list))))
516                                 (t
517                                  (cl-push (car c) type-list)
518                                  (cl-make-type-test temp (car c))))
519                           (or (cdr c) '(nil)))))
520                  clauses))))
521     (if (eq temp expr) body
522       (list 'let (list (list temp expr)) body))))
523
524 ;;;###autoload
525 (defmacro etypecase (expr &rest clauses)
526   "(etypecase EXPR CLAUSES...): like `typecase', but error if no case fits.
527 `otherwise'-clauses are not allowed."
528   (list* 'typecase expr (append clauses '((ecase-error-flag)))))
529
530
531 ;;; Blocks and exits.
532
533 ;;;###autoload
534 (defmacro block (name &rest body)
535   "(block NAME BODY...): define a lexically-scoped block named NAME.
536 NAME may be any symbol.  Code inside the BODY forms can call `return-from'
537 to jump prematurely out of the block.  This differs from `catch' and `throw'
538 in two respects:  First, the NAME is an unevaluated symbol rather than a
539 quoted symbol or other form; and second, NAME is lexically rather than
540 dynamically scoped:  Only references to it within BODY will work.  These
541 references may appear inside macro expansions, but not inside functions
542 called from BODY."
543   (if (cl-safe-expr-p (cons 'progn body)) (cons 'progn body)
544     (list 'cl-block-wrapper
545           (list* 'catch (list 'quote (intern (format "--cl-block-%s--" name)))
546                  body))))
547
548 (defvar cl-active-block-names nil)
549
550 (put 'cl-block-wrapper 'byte-compile 'cl-byte-compile-block)
551 (defun cl-byte-compile-block (cl-form)
552   (if (fboundp 'byte-compile-form-do-effect)  ; Check for optimizing compiler
553       (progn
554         (let* ((cl-entry (cons (nth 1 (nth 1 (nth 1 cl-form))) nil))
555                (cl-active-block-names (cons cl-entry cl-active-block-names))
556                (cl-body (byte-compile-top-level
557                          (cons 'progn (cddr (nth 1 cl-form))))))
558           (if (cdr cl-entry)
559               (byte-compile-form (list 'catch (nth 1 (nth 1 cl-form)) cl-body))
560             (byte-compile-form cl-body))))
561     (byte-compile-form (nth 1 cl-form))))
562
563 (put 'cl-block-throw 'byte-compile 'cl-byte-compile-throw)
564 (defun cl-byte-compile-throw (cl-form)
565   (let ((cl-found (assq (nth 1 (nth 1 cl-form)) cl-active-block-names)))
566     (if cl-found (setcdr cl-found t)))
567   (byte-compile-normal-call (cons 'throw (cdr cl-form))))
568
569 ;;;###autoload
570 (defmacro return (&optional res)
571   "(return [RESULT]): return from the block named nil.
572 This is equivalent to `(return-from nil RESULT)'."
573   (list 'return-from nil res))
574
575 ;;;###autoload
576 (defmacro return-from (name &optional res)
577   "(return-from NAME [RESULT]): return from the block named NAME.
578 This jump out to the innermost enclosing `(block NAME ...)' form,
579 returning RESULT from that form (or nil if RESULT is omitted).
580 This is compatible with Common Lisp, but note that `defun' and
581 `defmacro' do not create implicit blocks as they do in Common Lisp."
582   (let ((name2 (intern (format "--cl-block-%s--" name))))
583     (list 'cl-block-throw (list 'quote name2) res)))
584
585
586 ;;; The "loop" macro.
587
588 (defvar args) (defvar loop-accum-var) (defvar loop-accum-vars)
589 (defvar loop-bindings) (defvar loop-body) (defvar loop-destr-temps)
590 (defvar loop-finally) (defvar loop-finish-flag) (defvar loop-first-flag)
591 (defvar loop-initially) (defvar loop-map-form) (defvar loop-name)
592 (defvar loop-result) (defvar loop-result-explicit)
593 (defvar loop-result-var) (defvar loop-steps) (defvar loop-symbol-macs)
594
595 ;;;###autoload
596 (defmacro loop (&rest args)
597   "(loop CLAUSE...): The Common Lisp `loop' macro.
598 Valid clauses are:
599   for VAR from/upfrom/downfrom NUM to/upto/downto/above/below NUM by NUM,
600   for VAR in LIST by FUNC, for VAR on LIST by FUNC, for VAR = INIT then EXPR,
601   for VAR across ARRAY, repeat NUM, with VAR = INIT, while COND, until COND,
602   always COND, never COND, thereis COND, collect EXPR into VAR,
603   append EXPR into VAR, nconc EXPR into VAR, sum EXPR into VAR,
604   count EXPR into VAR, maximize EXPR into VAR, minimize EXPR into VAR,
605   if COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
606   unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
607   do EXPRS..., initially EXPRS..., finally EXPRS..., return EXPR,
608   finally return EXPR, named NAME."
609   (if (not (memq t (mapcar 'symbolp (delq nil (delq t (copy-list args))))))
610       (list 'block nil (list* 'while t args))
611     (let ((loop-name nil)       (loop-bindings nil)
612           (loop-body nil)       (loop-steps nil)
613           (loop-result nil)     (loop-result-explicit nil)
614           (loop-result-var nil) (loop-finish-flag nil)
615           (loop-accum-var nil)  (loop-accum-vars nil)
616           (loop-initially nil)  (loop-finally nil)
617           (loop-map-form nil)   (loop-first-flag nil)
618           (loop-destr-temps nil) (loop-symbol-macs nil))
619       (setq args (append args '(cl-end-loop)))
620       (while (not (eq (car args) 'cl-end-loop)) (cl-parse-loop-clause))
621       (if loop-finish-flag
622           (cl-push (list (list loop-finish-flag t)) loop-bindings))
623       (if loop-first-flag
624           (progn (cl-push (list (list loop-first-flag t)) loop-bindings)
625                  (cl-push (list 'setq loop-first-flag nil) loop-steps)))
626       (let* ((epilogue (nconc (nreverse loop-finally)
627                               (list (or loop-result-explicit loop-result))))
628              (ands (cl-loop-build-ands (nreverse loop-body)))
629              (while-body (nconc (cadr ands) (nreverse loop-steps)))
630              (body (append
631                     (nreverse loop-initially)
632                     (list (if loop-map-form
633                               (list 'block '--cl-finish--
634                                     (subst
635                                      (if (eq (car ands) t) while-body
636                                        (cons (list 'or (car ands)
637                                                    '(return-from --cl-finish--
638                                                       nil))
639                                              while-body))
640                                      '--cl-map loop-map-form))
641                             (list* 'while (car ands) while-body)))
642                     (if loop-finish-flag
643                         (if (equal epilogue '(nil)) (list loop-result-var)
644                           (list (list 'if loop-finish-flag
645                                       (cons 'progn epilogue) loop-result-var)))
646                       epilogue))))
647         (if loop-result-var (cl-push (list loop-result-var) loop-bindings))
648         (while loop-bindings
649           (if (cdar loop-bindings)
650               (setq body (list (cl-loop-let (cl-pop loop-bindings) body t)))
651             (let ((lets nil))
652               (while (and loop-bindings
653                           (not (cdar loop-bindings)))
654                 (cl-push (car (cl-pop loop-bindings)) lets))
655               (setq body (list (cl-loop-let lets body nil))))))
656         (if loop-symbol-macs
657             (setq body (list (list* 'symbol-macrolet loop-symbol-macs body))))
658         (list* 'block loop-name body)))))
659
660 (defun cl-parse-loop-clause ()   ; uses args, loop-*
661   (let ((word (cl-pop args))
662         (hash-types '(hash-key hash-keys hash-value hash-values))
663         (key-types '(key-code key-codes key-seq key-seqs
664                      key-binding key-bindings)))
665     (cond
666
667      ((null args)
668       (error "Malformed `loop' macro"))
669
670      ((eq word 'named)
671       (setq loop-name (cl-pop args)))
672
673      ((eq word 'initially)
674       (if (memq (car args) '(do doing)) (cl-pop args))
675       (or (consp (car args)) (error "Syntax error on `initially' clause"))
676       (while (consp (car args))
677         (cl-push (cl-pop args) loop-initially)))
678
679      ((eq word 'finally)
680       (if (eq (car args) 'return)
681           (setq loop-result-explicit (or (cl-pop2 args) '(quote nil)))
682         (if (memq (car args) '(do doing)) (cl-pop args))
683         (or (consp (car args)) (error "Syntax error on `finally' clause"))
684         (if (and (eq (caar args) 'return) (null loop-name))
685             (setq loop-result-explicit (or (nth 1 (cl-pop args)) '(quote nil)))
686           (while (consp (car args))
687             (cl-push (cl-pop args) loop-finally)))))
688
689      ((memq word '(for as))
690       (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
691             (ands nil))
692         (while
693             (let ((var (or (cl-pop args) (gensym))))
694               (setq word (cl-pop args))
695               (if (eq word 'being) (setq word (cl-pop args)))
696               (if (memq word '(the each)) (setq word (cl-pop args)))
697               (if (memq word '(buffer buffers))
698                   (setq word 'in args (cons '(buffer-list) args)))
699               (cond
700
701                ((memq word '(from downfrom upfrom to downto upto
702                              above below by))
703                 (cl-push word args)
704                 (if (memq (car args) '(downto above))
705                     (error "Must specify `from' value for downward loop"))
706                 (let* ((down (or (eq (car args) 'downfrom)
707                                  (memq (caddr args) '(downto above))))
708                        (excl (or (memq (car args) '(above below))
709                                  (memq (caddr args) '(above below))))
710                        (start (and (memq (car args) '(from upfrom downfrom))
711                                    (cl-pop2 args)))
712                        (end (and (memq (car args)
713                                        '(to upto downto above below))
714                                  (cl-pop2 args)))
715                        (step (and (eq (car args) 'by) (cl-pop2 args)))
716                        (end-var (and (not (cl-const-expr-p end)) (gensym)))
717                        (step-var (and (not (cl-const-expr-p step))
718                                       (gensym))))
719                   (and step (numberp step) (<= step 0)
720                        (error "Loop `by' value is not positive: %s" step))
721                   (cl-push (list var (or start 0)) loop-for-bindings)
722                   (if end-var (cl-push (list end-var end) loop-for-bindings))
723                   (if step-var (cl-push (list step-var step)
724                                         loop-for-bindings))
725                   (if end
726                       (cl-push (list
727                                 (if down (if excl '> '>=) (if excl '< '<=))
728                                 var (or end-var end)) loop-body))
729                   (cl-push (list var (list (if down '- '+) var
730                                            (or step-var step 1)))
731                            loop-for-steps)))
732
733                ((memq word '(in in-ref on))
734                 (let* ((on (eq word 'on))
735                        (temp (if (and on (symbolp var)) var (gensym))))
736                   (cl-push (list temp (cl-pop args)) loop-for-bindings)
737                   (cl-push (list 'consp temp) loop-body)
738                   (if (eq word 'in-ref)
739                       (cl-push (list var (list 'car temp)) loop-symbol-macs)
740                     (or (eq temp var)
741                         (progn
742                           (cl-push (list var nil) loop-for-bindings)
743                           (cl-push (list var (if on temp (list 'car temp)))
744                                    loop-for-sets))))
745                   (cl-push (list temp
746                                  (if (eq (car args) 'by)
747                                      (let ((step (cl-pop2 args)))
748                                        (if (and (memq (car-safe step)
749                                                       '(quote function
750                                                               function*))
751                                                 (symbolp (nth 1 step)))
752                                            (list (nth 1 step) temp)
753                                          (list 'funcall step temp)))
754                                    (list 'cdr temp)))
755                            loop-for-steps)))
756
757                ((eq word '=)
758                 (let* ((start (cl-pop args))
759                        (then (if (eq (car args) 'then) (cl-pop2 args) start)))
760                   (cl-push (list var nil) loop-for-bindings)
761                   (if (or ands (eq (car args) 'and))
762                       (progn
763                         (cl-push (list var
764                                        (list 'if
765                                              (or loop-first-flag
766                                                  (setq loop-first-flag
767                                                        (gensym)))
768                                              start var))
769                                  loop-for-sets)
770                         (cl-push (list var then) loop-for-steps))
771                     (cl-push (list var
772                                    (if (eq start then) start
773                                      (list 'if
774                                            (or loop-first-flag
775                                                (setq loop-first-flag (gensym)))
776                                            start then)))
777                              loop-for-sets))))
778
779                ((memq word '(across across-ref))
780                 (let ((temp-vec (gensym)) (temp-idx (gensym)))
781                   (cl-push (list temp-vec (cl-pop args)) loop-for-bindings)
782                   (cl-push (list temp-idx -1) loop-for-bindings)
783                   (cl-push (list '< (list 'setq temp-idx (list '1+ temp-idx))
784                                  (list 'length temp-vec)) loop-body)
785                   (if (eq word 'across-ref)
786                       (cl-push (list var (list 'aref temp-vec temp-idx))
787                                loop-symbol-macs)
788                     (cl-push (list var nil) loop-for-bindings)
789                     (cl-push (list var (list 'aref temp-vec temp-idx))
790                              loop-for-sets))))
791
792                ((memq word '(element elements))
793                 (let ((ref (or (memq (car args) '(in-ref of-ref))
794                                (and (not (memq (car args) '(in of)))
795                                     (error "Expected `of'"))))
796                       (seq (cl-pop2 args))
797                       (temp-seq (gensym))
798                       (temp-idx (if (eq (car args) 'using)
799                                     (if (and (= (length (cadr args)) 2)
800                                              (eq (caadr args) 'index))
801                                         (cadr (cl-pop2 args))
802                                       (error "Bad `using' clause"))
803                                   (gensym))))
804                   (cl-push (list temp-seq seq) loop-for-bindings)
805                   (cl-push (list temp-idx 0) loop-for-bindings)
806                   (if ref
807                       (let ((temp-len (gensym)))
808                         (cl-push (list temp-len (list 'length temp-seq))
809                                  loop-for-bindings)
810                         (cl-push (list var (list 'elt temp-seq temp-idx))
811                                  loop-symbol-macs)
812                         (cl-push (list '< temp-idx temp-len) loop-body))
813                     (cl-push (list var nil) loop-for-bindings)
814                     (cl-push (list 'and temp-seq
815                                    (list 'or (list 'consp temp-seq)
816                                          (list '< temp-idx
817                                                (list 'length temp-seq))))
818                              loop-body)
819                     (cl-push (list var (list 'if (list 'consp temp-seq)
820                                              (list 'pop temp-seq)
821                                              (list 'aref temp-seq temp-idx)))
822                              loop-for-sets))
823                   (cl-push (list temp-idx (list '1+ temp-idx))
824                            loop-for-steps)))
825
826                ((memq word hash-types)
827                 (or (memq (car args) '(in of)) (error "Expected `of'"))
828                 (let* ((table (cl-pop2 args))
829                        (other (if (eq (car args) 'using)
830                                   (if (and (= (length (cadr args)) 2)
831                                            (memq (caadr args) hash-types)
832                                            (not (eq (caadr args) word)))
833                                       (cadr (cl-pop2 args))
834                                     (error "Bad `using' clause"))
835                                 (gensym))))
836                   (if (memq word '(hash-value hash-values))
837                       (setq var (prog1 other (setq other var))))
838                   (setq loop-map-form
839                         (list 'maphash (list 'function
840                                              (list* 'lambda (list var other)
841                                                     '--cl-map)) table))))
842
843                ((memq word '(symbol present-symbol external-symbol
844                              symbols present-symbols external-symbols))
845                 (let ((ob (and (memq (car args) '(in of)) (cl-pop2 args))))
846                   (setq loop-map-form
847                         (list 'mapatoms (list 'function
848                                               (list* 'lambda (list var)
849                                                      '--cl-map)) ob))))
850
851                ((memq word '(overlay overlays extent extents))
852                 (let ((buf nil) (from nil) (to nil))
853                   (while (memq (car args) '(in of from to))
854                     (cond ((eq (car args) 'from) (setq from (cl-pop2 args)))
855                           ((eq (car args) 'to) (setq to (cl-pop2 args)))
856                           (t (setq buf (cl-pop2 args)))))
857                   (setq loop-map-form
858                         (list 'cl-map-extents
859                               (list 'function (list 'lambda (list var (gensym))
860                                                     '(progn . --cl-map) nil))
861                               buf from to))))
862
863                ((memq word '(interval intervals))
864                 (let ((buf nil) (prop nil) (from nil) (to nil)
865                       (var1 (gensym)) (var2 (gensym)))
866                   (while (memq (car args) '(in of property from to))
867                     (cond ((eq (car args) 'from) (setq from (cl-pop2 args)))
868                           ((eq (car args) 'to) (setq to (cl-pop2 args)))
869                           ((eq (car args) 'property)
870                            (setq prop (cl-pop2 args)))
871                           (t (setq buf (cl-pop2 args)))))
872                   (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
873                       (setq var1 (car var) var2 (cdr var))
874                     (cl-push (list var (list 'cons var1 var2)) loop-for-sets))
875                   (setq loop-map-form
876                         (list 'cl-map-intervals
877                               (list 'function (list 'lambda (list var1 var2)
878                                                     '(progn . --cl-map)))
879                               buf prop from to))))
880
881                ((memq word key-types)
882                 (or (memq (car args) '(in of)) (error "Expected `of'"))
883                 (let ((map (cl-pop2 args))
884                       (other (if (eq (car args) 'using)
885                                  (if (and (= (length (cadr args)) 2)
886                                           (memq (caadr args) key-types)
887                                           (not (eq (caadr args) word)))
888                                      (cadr (cl-pop2 args))
889                                    (error "Bad `using' clause"))
890                                (gensym))))
891                   (if (memq word '(key-binding key-bindings))
892                       (setq var (prog1 other (setq other var))))
893                   (setq loop-map-form
894                         (list (if (memq word '(key-seq key-seqs))
895                                   'cl-map-keymap-recursively 'cl-map-keymap)
896                               (list 'function (list* 'lambda (list var other)
897                                                      '--cl-map)) map))))
898
899                ((memq word '(frame frames screen screens))
900                 (let ((temp (gensym)))
901                   (cl-push (list var '(selected-frame))
902                            loop-for-bindings)
903                   (cl-push (list temp nil) loop-for-bindings)
904                   (cl-push (list 'prog1 (list 'not (list 'eq var temp))
905                                  (list 'or temp (list 'setq temp var)))
906                            loop-body)
907                   (cl-push (list var (list 'next-frame var))
908                            loop-for-steps)))
909
910                ((memq word '(window windows))
911                 (let ((scr (and (memq (car args) '(in of)) (cl-pop2 args)))
912                       (temp (gensym)))
913                   (cl-push (list var (if scr
914                                          (list 'frame-selected-window scr)
915                                        '(selected-window)))
916                            loop-for-bindings)
917                   (cl-push (list temp nil) loop-for-bindings)
918                   (cl-push (list 'prog1 (list 'not (list 'eq var temp))
919                                  (list 'or temp (list 'setq temp var)))
920                            loop-body)
921                   (cl-push (list var (list 'next-window var)) loop-for-steps)))
922
923                (t
924                 (let ((handler (and (symbolp word)
925                                     (get word 'cl-loop-for-handler))))
926                   (if handler
927                       (funcall handler var)
928                     (error "Expected a `for' preposition, found %s" word)))))
929               (eq (car args) 'and))
930           (setq ands t)
931           (cl-pop args))
932         (if (and ands loop-for-bindings)
933             (cl-push (nreverse loop-for-bindings) loop-bindings)
934           (setq loop-bindings (nconc (mapcar 'list loop-for-bindings)
935                                      loop-bindings)))
936         (if loop-for-sets
937             (cl-push (list 'progn
938                            (cl-loop-let (nreverse loop-for-sets) 'setq ands)
939                            t) loop-body))
940         (if loop-for-steps
941             (cl-push (cons (if ands 'psetq 'setq)
942                            (apply 'append (nreverse loop-for-steps)))
943                      loop-steps))))
944
945      ((eq word 'repeat)
946       (let ((temp (gensym)))
947         (cl-push (list (list temp (cl-pop args))) loop-bindings)
948         (cl-push (list '>= (list 'setq temp (list '1- temp)) 0) loop-body)))
949
950      ((eq word 'collect)
951       (let ((what (cl-pop args))
952             (var (cl-loop-handle-accum nil 'nreverse)))
953         (if (eq var loop-accum-var)
954             (cl-push (list 'progn (list 'push what var) t) loop-body)
955           (cl-push (list 'progn
956                          (list 'setq var (list 'nconc var (list 'list what)))
957                          t) loop-body))))
958
959      ((memq word '(nconc nconcing append appending))
960       (let ((what (cl-pop args))
961             (var (cl-loop-handle-accum nil 'nreverse)))
962         (cl-push (list 'progn
963                        (list 'setq var
964                              (if (eq var loop-accum-var)
965                                  (list 'nconc
966                                        (list (if (memq word '(nconc nconcing))
967                                                  'nreverse 'reverse)
968                                              what)
969                                        var)
970                                (list (if (memq word '(nconc nconcing))
971                                          'nconc 'append)
972                                      var what))) t) loop-body)))
973
974      ((memq word '(concat concating))
975       (let ((what (cl-pop args))
976             (var (cl-loop-handle-accum "")))
977         (cl-push (list 'progn (list 'callf 'concat var what) t) loop-body)))
978
979      ((memq word '(vconcat vconcating))
980       (let ((what (cl-pop args))
981             (var (cl-loop-handle-accum [])))
982         (cl-push (list 'progn (list 'callf 'vconcat var what) t) loop-body)))
983
984      ((memq word '(sum summing))
985       (let ((what (cl-pop args))
986             (var (cl-loop-handle-accum 0)))
987         (cl-push (list 'progn (list 'incf var what) t) loop-body)))
988
989      ((memq word '(count counting))
990       (let ((what (cl-pop args))
991             (var (cl-loop-handle-accum 0)))
992         (cl-push (list 'progn (list 'if what (list 'incf var)) t) loop-body)))
993
994      ((memq word '(minimize minimizing maximize maximizing))
995       (let* ((what (cl-pop args))
996              (temp (if (cl-simple-expr-p what) what (gensym)))
997              (var (cl-loop-handle-accum nil))
998              (func (intern (substring (symbol-name word) 0 3)))
999              (set (list 'setq var (list 'if var (list func var temp) temp))))
1000         (cl-push (list 'progn (if (eq temp what) set
1001                                 (list 'let (list (list temp what)) set))
1002                        t) loop-body)))
1003
1004      ((eq word 'with)
1005       (let ((bindings nil))
1006         (while (progn (cl-push (list (cl-pop args)
1007                                      (and (eq (car args) '=) (cl-pop2 args)))
1008                                bindings)
1009                       (eq (car args) 'and))
1010           (cl-pop args))
1011         (cl-push (nreverse bindings) loop-bindings)))
1012
1013      ((eq word 'while)
1014       (cl-push (cl-pop args) loop-body))
1015
1016      ((eq word 'until)
1017       (cl-push (list 'not (cl-pop args)) loop-body))
1018
1019      ((eq word 'always)
1020       (or loop-finish-flag (setq loop-finish-flag (gensym)))
1021       (cl-push (list 'setq loop-finish-flag (cl-pop args)) loop-body)
1022       (setq loop-result t))
1023
1024      ((eq word 'never)
1025       (or loop-finish-flag (setq loop-finish-flag (gensym)))
1026       (cl-push (list 'setq loop-finish-flag (list 'not (cl-pop args)))
1027                loop-body)
1028       (setq loop-result t))
1029
1030      ((eq word 'thereis)
1031       (or loop-finish-flag (setq loop-finish-flag (gensym)))
1032       (or loop-result-var (setq loop-result-var (gensym)))
1033       (cl-push (list 'setq loop-finish-flag
1034                      (list 'not (list 'setq loop-result-var (cl-pop args))))
1035                loop-body))
1036
1037      ((memq word '(if when unless))
1038       (let* ((cond (cl-pop args))
1039              (then (let ((loop-body nil))
1040                      (cl-parse-loop-clause)
1041                      (cl-loop-build-ands (nreverse loop-body))))
1042              (else (let ((loop-body nil))
1043                      (if (eq (car args) 'else)
1044                          (progn (cl-pop args) (cl-parse-loop-clause)))
1045                      (cl-loop-build-ands (nreverse loop-body))))
1046              (simple (and (eq (car then) t) (eq (car else) t))))
1047         (if (eq (car args) 'end) (cl-pop args))
1048         (if (eq word 'unless) (setq then (prog1 else (setq else then))))
1049         (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
1050                           (if simple (nth 1 else) (list (nth 2 else))))))
1051           (if (cl-expr-contains form 'it)
1052               (let ((temp (gensym)))
1053                 (cl-push (list temp) loop-bindings)
1054                 (setq form (list* 'if (list 'setq temp cond)
1055                                   (subst temp 'it form))))
1056             (setq form (list* 'if cond form)))
1057           (cl-push (if simple (list 'progn form t) form) loop-body))))
1058
1059      ((memq word '(do doing))
1060       (let ((body nil))
1061         (or (consp (car args)) (error "Syntax error on `do' clause"))
1062         (while (consp (car args)) (cl-push (cl-pop args) body))
1063         (cl-push (cons 'progn (nreverse (cons t body))) loop-body)))
1064
1065      ((eq word 'return)
1066       (or loop-finish-flag (setq loop-finish-flag (gensym)))
1067       (or loop-result-var (setq loop-result-var (gensym)))
1068       (cl-push (list 'setq loop-result-var (cl-pop args)
1069                      loop-finish-flag nil) loop-body))
1070
1071      (t
1072       (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
1073         (or handler (error "Expected a loop keyword, found %s" word))
1074         (funcall handler))))
1075     (if (eq (car args) 'and)
1076         (progn (cl-pop args) (cl-parse-loop-clause)))))
1077
1078 (defun cl-loop-let (specs body par)   ; uses loop-*
1079   (let ((p specs) (temps nil) (new nil))
1080     (while (and p (or (symbolp (car-safe (car p))) (null (cadar p))))
1081       (setq p (cdr p)))
1082     (and par p
1083          (progn
1084            (setq par nil p specs)
1085            (while p
1086              (or (cl-const-expr-p (cadar p))
1087                  (let ((temp (gensym)))
1088                    (cl-push (list temp (cadar p)) temps)
1089                    (setcar (cdar p) temp)))
1090              (setq p (cdr p)))))
1091     (while specs
1092       (if (and (consp (car specs)) (listp (caar specs)))
1093           (let* ((spec (caar specs)) (nspecs nil)
1094                  (expr (cadr (cl-pop specs)))
1095                  (temp (cdr (or (assq spec loop-destr-temps)
1096                                 (car (cl-push (cons spec (or (last spec 0)
1097                                                              (gensym)))
1098                                               loop-destr-temps))))))
1099             (cl-push (list temp expr) new)
1100             (while (consp spec)
1101               (cl-push (list (cl-pop spec)
1102                              (and expr (list (if spec 'pop 'car) temp)))
1103                        nspecs))
1104             (setq specs (nconc (nreverse nspecs) specs)))
1105         (cl-push (cl-pop specs) new)))
1106     (if (eq body 'setq)
1107         (let ((set (cons (if par 'psetq 'setq) (apply 'nconc (nreverse new)))))
1108           (if temps (list 'let* (nreverse temps) set) set))
1109       (list* (if par 'let 'let*)
1110              (nconc (nreverse temps) (nreverse new)) body))))
1111
1112 (defun cl-loop-handle-accum (def &optional func)   ; uses args, loop-*
1113   (if (eq (car args) 'into)
1114       (let ((var (cl-pop2 args)))
1115         (or (memq var loop-accum-vars)
1116             (progn (cl-push (list (list var def)) loop-bindings)
1117                    (cl-push var loop-accum-vars)))
1118         var)
1119     (or loop-accum-var
1120         (progn
1121           (cl-push (list (list (setq loop-accum-var (gensym)) def))
1122                    loop-bindings)
1123           (setq loop-result (if func (list func loop-accum-var)
1124                               loop-accum-var))
1125           loop-accum-var))))
1126
1127 (defun cl-loop-build-ands (clauses)
1128   (let ((ands nil)
1129         (body nil))
1130     (while clauses
1131       (if (and (eq (car-safe (car clauses)) 'progn)
1132                (eq (car (last (car clauses))) t))
1133           (if (cdr clauses)
1134               (setq clauses (cons (nconc (butlast (car clauses))
1135                                          (if (eq (car-safe (cadr clauses))
1136                                                  'progn)
1137                                              (cdadr clauses)
1138                                            (list (cadr clauses))))
1139                                   (cddr clauses)))
1140             (setq body (cdr (butlast (cl-pop clauses)))))
1141         (cl-push (cl-pop clauses) ands)))
1142     (setq ands (or (nreverse ands) (list t)))
1143     (list (if (cdr ands) (cons 'and ands) (car ands))
1144           body
1145           (let ((full (if body
1146                           (append ands (list (cons 'progn (append body '(t)))))
1147                         ands)))
1148             (if (cdr full) (cons 'and full) (car full))))))
1149
1150
1151 ;;; Other iteration control structures.
1152
1153 ;;;###autoload
1154 (defmacro do (steps endtest &rest body)
1155   "The Common Lisp `do' loop.
1156 Format is: (do ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1157   (cl-expand-do-loop steps endtest body nil))
1158
1159 ;;;###autoload
1160 (defmacro do* (steps endtest &rest body)
1161   "The Common Lisp `do*' loop.
1162 Format is: (do* ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1163   (cl-expand-do-loop steps endtest body t))
1164
1165 (defun cl-expand-do-loop (steps endtest body star)
1166   (list 'block nil
1167         (list* (if star 'let* 'let)
1168                (mapcar (function (lambda (c)
1169                                    (if (consp c) (list (car c) (nth 1 c)) c)))
1170                        steps)
1171                (list* 'while (list 'not (car endtest))
1172                       (append body
1173                               (let ((sets (mapcar
1174                                            (function
1175                                             (lambda (c)
1176                                               (and (consp c) (cdr (cdr c))
1177                                                    (list (car c) (nth 2 c)))))
1178                                            steps)))
1179                                 (setq sets (delq nil sets))
1180                                 (and sets
1181                                      (list (cons (if (or star (not (cdr sets)))
1182                                                      'setq 'psetq)
1183                                                  (apply 'append sets)))))))
1184                (or (cdr endtest) '(nil)))))
1185
1186 ;;;###autoload
1187 (defmacro dolist (spec &rest body)
1188   "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
1189 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1190 Then evaluate RESULT to get return value, default nil."
1191   (let ((temp (gensym "--dolist-temp--")))
1192     (list 'block nil
1193           (list* 'let (list (list temp (nth 1 spec)) (car spec))
1194                  (list* 'while temp (list 'setq (car spec) (list 'car temp))
1195                         (append body (list (list 'setq temp
1196                                                  (list 'cdr temp)))))
1197                  (if (cdr (cdr spec))
1198                      (cons (list 'setq (car spec) nil) (cdr (cdr spec)))
1199                    '(nil))))))
1200
1201 ;;;###autoload
1202 (defmacro dotimes (spec &rest body)
1203   "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
1204 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1205 to COUNT, exclusive.  Then evaluate RESULT to get return value, default
1206 nil."
1207   (let ((temp (gensym "--dotimes-temp--")))
1208     (list 'block nil
1209           (list* 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
1210                  (list* 'while (list '< (car spec) temp)
1211                         (append body (list (list 'incf (car spec)))))
1212                  (or (cdr (cdr spec)) '(nil))))))
1213
1214 ;;;###autoload
1215 (defmacro do-symbols (spec &rest body)
1216   "(dosymbols (VAR [OBARRAY [RESULT]]) BODY...): loop over all symbols.
1217 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1218 from OBARRAY."
1219   ;; Apparently this doesn't have an implicit block.
1220   (list 'block nil
1221         (list 'let (list (car spec))
1222               (list* 'mapatoms
1223                      (list 'function (list* 'lambda (list (car spec)) body))
1224                      (and (cadr spec) (list (cadr spec))))
1225               (caddr spec))))
1226
1227 ;;;###autoload
1228 (defmacro do-all-symbols (spec &rest body)
1229   (list* 'do-symbols (list (car spec) nil (cadr spec)) body))
1230
1231
1232 ;;; Assignments.
1233
1234 ;;;###autoload
1235 (defmacro psetq (&rest args)
1236   "(psetq SYM VAL SYM VAL ...): set SYMs to the values VALs in parallel.
1237 This is like `setq', except that all VAL forms are evaluated (in order)
1238 before assigning any symbols SYM to the corresponding values."
1239   (cons 'psetf args))
1240
1241
1242 ;;; Binding control structures.
1243
1244 ;;;###autoload
1245 (defmacro progv (symbols values &rest body)
1246   "(progv SYMBOLS VALUES BODY...): bind SYMBOLS to VALUES dynamically in BODY.
1247 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1248 Each SYMBOL in the first list is bound to the corresponding VALUE in the
1249 second list (or made unbound if VALUES is shorter than SYMBOLS); then the
1250 BODY forms are executed and their result is returned.  This is much like
1251 a `let' form, except that the list of symbols can be computed at run-time."
1252   (list 'let '((cl-progv-save nil))
1253         (list 'unwind-protect
1254               (list* 'progn (list 'cl-progv-before symbols values) body)
1255               '(cl-progv-after))))
1256
1257 ;;; This should really have some way to shadow 'byte-compile properties, etc.
1258 ;;;###autoload
1259 (defmacro flet (bindings &rest body)
1260   "(flet ((FUNC ARGLIST BODY...) ...) FORM...): make temporary function defns.
1261 This is an analogue of `let' that operates on the function cell of FUNC
1262 rather than its value cell.  The FORMs are evaluated with the specified
1263 function definitions in place, then the definitions are undone (the FUNCs
1264 go back to their previous definitions, or lack thereof)."
1265   (list* 'letf*
1266          (mapcar
1267           (function
1268            (lambda (x)
1269              (if (or (and (fboundp (car x))
1270                           (eq (car-safe (symbol-function (car x))) 'macro))
1271                      (cdr (assq (car x) cl-macro-environment)))
1272                  (error "Use `labels', not `flet', to rebind macro names"))
1273              (let ((func (list 'function*
1274                                (list 'lambda (cadr x)
1275                                      (list* 'block (car x) (cddr x))))))
1276                (if (and (cl-compiling-file)
1277                         (boundp 'byte-compile-function-environment))
1278                    (cl-push (cons (car x) (eval func))
1279                             byte-compile-function-environment))
1280                (list (list 'symbol-function (list 'quote (car x))) func))))
1281           bindings)
1282          body))
1283
1284 ;;;###autoload
1285 (defmacro labels (bindings &rest body)
1286   "(labels ((FUNC ARGLIST BODY...) ...) FORM...): make temporary func bindings.
1287 This is like `flet', except the bindings are lexical instead of dynamic.
1288 Unlike `flet', this macro is fully complaint with the Common Lisp standard."
1289   (let ((vars nil) (sets nil) (cl-macro-environment cl-macro-environment))
1290     (while bindings
1291       (let ((var (gensym)))
1292         (cl-push var vars)
1293         (cl-push (list 'function* (cons 'lambda (cdar bindings))) sets)
1294         (cl-push var sets)
1295         (cl-push (list (car (cl-pop bindings)) 'lambda '(&rest cl-labels-args)
1296                        (list 'list* '(quote funcall) (list 'quote var)
1297                              'cl-labels-args))
1298                  cl-macro-environment)))
1299     (cl-macroexpand-all (list* 'lexical-let vars (cons (cons 'setq sets) body))
1300                         cl-macro-environment)))
1301
1302 ;; The following ought to have a better definition for use with newer
1303 ;; byte compilers.
1304 ;;;###autoload
1305 (defmacro macrolet (bindings &rest body)
1306   "(macrolet ((NAME ARGLIST BODY...) ...) FORM...): make temporary macro defns.
1307 This is like `flet', but for macros instead of functions."
1308   (if (cdr bindings)
1309       (list 'macrolet
1310             (list (car bindings)) (list* 'macrolet (cdr bindings) body))
1311     (if (null bindings) (cons 'progn body)
1312       (let* ((name (caar bindings))
1313              (res (cl-transform-lambda (cdar bindings) name)))
1314         (eval (car res))
1315         (cl-macroexpand-all (cons 'progn body)
1316                             (cons (list* name 'lambda (cdr res))
1317                                   cl-macro-environment))))))
1318
1319 ;;;###autoload
1320 (defmacro symbol-macrolet (bindings &rest body)
1321   "(symbol-macrolet ((NAME EXPANSION) ...) FORM...): make symbol macro defns.
1322 Within the body FORMs, references to the variable NAME will be replaced
1323 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...)."
1324   (if (cdr bindings)
1325       (list 'symbol-macrolet
1326             (list (car bindings)) (list* 'symbol-macrolet (cdr bindings) body))
1327     (if (null bindings) (cons 'progn body)
1328       (cl-macroexpand-all (cons 'progn body)
1329                           (cons (list (symbol-name (caar bindings))
1330                                       (cadar bindings))
1331                                 cl-macro-environment)))))
1332
1333 (defvar cl-closure-vars nil)
1334 ;;;###autoload
1335 (defmacro lexical-let (bindings &rest body)
1336   "(lexical-let BINDINGS BODY...): like `let', but lexically scoped.
1337 The main visible difference is that lambdas inside BODY will create
1338 lexical closures as in Common Lisp."
1339   (let* ((cl-closure-vars cl-closure-vars)
1340          (vars (mapcar (function
1341                         (lambda (x)
1342                           (or (consp x) (setq x (list x)))
1343                           (cl-push (gensym (format "--%s--" (car x)))
1344                                    cl-closure-vars)
1345                           (list (car x) (cadr x) (car cl-closure-vars))))
1346                        bindings))
1347          (ebody 
1348           (cl-macroexpand-all
1349            (cons 'progn body)
1350            (nconc (mapcar (function (lambda (x)
1351                                       (list (symbol-name (car x))
1352                                             (list 'symbol-value (caddr x))
1353                                             t))) vars)
1354                   (list '(defun . cl-defun-expander))
1355                   cl-macro-environment))))
1356     (if (not (get (car (last cl-closure-vars)) 'used))
1357         (list 'let (mapcar (function (lambda (x)
1358                                        (list (caddr x) (cadr x)))) vars)
1359               (sublis (mapcar (function (lambda (x)
1360                                           (cons (caddr x)
1361                                                 (list 'quote (caddr x)))))
1362                               vars)
1363                       ebody))
1364       (list 'let (mapcar (function (lambda (x)
1365                                      (list (caddr x)
1366                                            (list 'make-symbol
1367                                                  (format "--%s--" (car x))))))
1368                          vars)
1369             (apply 'append '(setf)
1370                    (mapcar (function
1371                             (lambda (x)
1372                               (list (list 'symbol-value (caddr x)) (cadr x))))
1373                            vars))
1374             ebody))))
1375
1376 ;;;###autoload
1377 (defmacro lexical-let* (bindings &rest body)
1378   "(lexical-let* BINDINGS BODY...): like `let*', but lexically scoped.
1379 The main visible difference is that lambdas inside BODY will create
1380 lexical closures as in Common Lisp."
1381   (if (null bindings) (cons 'progn body)
1382     (setq bindings (reverse bindings))
1383     (while bindings
1384       (setq body (list (list* 'lexical-let (list (cl-pop bindings)) body))))
1385     (car body)))
1386
1387 (defun cl-defun-expander (func &rest rest)
1388   (list 'progn
1389         (list 'defalias (list 'quote func)
1390               (list 'function (cons 'lambda rest)))
1391         (list 'quote func)))
1392
1393
1394 ;;; Multiple values.
1395
1396 ;;;###autoload
1397 (defmacro multiple-value-bind (vars form &rest body)
1398   "(multiple-value-bind (SYM SYM...) FORM BODY): collect multiple return values.
1399 FORM must return a list; the BODY is then executed with the first N elements
1400 of this list bound (`let'-style) to each of the symbols SYM in turn.  This
1401 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
1402 simulate true multiple return values.  For compatibility, (values A B C) is
1403 a synonym for (list A B C)."
1404   (let ((temp (gensym)) (n -1))
1405     (list* 'let* (cons (list temp form)
1406                        (mapcar (function
1407                                 (lambda (v)
1408                                   (list v (list 'nth (setq n (1+ n)) temp))))
1409                                vars))
1410            body)))
1411
1412 ;;;###autoload
1413 (defmacro multiple-value-setq (vars form)
1414   "(multiple-value-setq (SYM SYM...) FORM): collect multiple return values.
1415 FORM must return a list; the first N elements of this list are stored in
1416 each of the symbols SYM in turn.  This is analogous to the Common Lisp
1417 `multiple-value-setq' macro, using lists to simulate true multiple return
1418 values.  For compatibility, (values A B C) is a synonym for (list A B C)."
1419   (cond ((null vars) (list 'progn form nil))
1420         ((null (cdr vars)) (list 'setq (car vars) (list 'car form)))
1421         (t
1422          (let* ((temp (gensym)) (n 0))
1423            (list 'let (list (list temp form))
1424                  (list 'prog1 (list 'setq (cl-pop vars) (list 'car temp))
1425                        (cons 'setq (apply 'nconc
1426                                           (mapcar (function
1427                                                    (lambda (v)
1428                                                      (list v (list
1429                                                               'nth
1430                                                               (setq n (1+ n))
1431                                                               temp))))
1432                                                   vars)))))))))
1433
1434
1435 ;;; Declarations.
1436
1437 ;;;###autoload
1438 (defmacro locally (&rest body) (cons 'progn body))
1439 ;;;###autoload
1440 (defmacro the (type form) form)
1441
1442 (defvar cl-proclaim-history t)    ; for future compilers
1443 (defvar cl-declare-stack t)       ; for future compilers
1444
1445 (defun cl-do-proclaim (spec hist)
1446   (and hist (listp cl-proclaim-history) (cl-push spec cl-proclaim-history))
1447   (cond ((eq (car-safe spec) 'special)
1448          (if (boundp 'byte-compile-bound-variables)
1449              (setq byte-compile-bound-variables
1450                    ;; todo: this should compute correct binding bits vs. 0
1451                    (append (mapcar #'(lambda (v) (cons v 0)) 
1452                                    (cdr spec))
1453                            byte-compile-bound-variables))))
1454
1455         ((eq (car-safe spec) 'inline)
1456          (while (setq spec (cdr spec))
1457            (or (memq (get (car spec) 'byte-optimizer)
1458                      '(nil byte-compile-inline-expand))
1459                (error "%s already has a byte-optimizer, can't make it inline"
1460                       (car spec)))
1461            (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
1462
1463         ((eq (car-safe spec) 'notinline)
1464          (while (setq spec (cdr spec))
1465            (if (eq (get (car spec) 'byte-optimizer)
1466                    'byte-compile-inline-expand)
1467                (put (car spec) 'byte-optimizer nil))))
1468
1469         ((eq (car-safe spec) 'optimize)
1470          (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
1471                             '((0 nil) (1 t) (2 t) (3 t))))
1472                (safety (assq (nth 1 (assq 'safety (cdr spec)))
1473                              '((0 t) (1 t) (2 t) (3 nil)))))
1474            (if speed (setq cl-optimize-speed (car speed)
1475                            byte-optimize (nth 1 speed)))
1476            (if safety (setq cl-optimize-safety (car safety)
1477                             byte-compile-delete-errors (nth 1 safety)))))
1478
1479         ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
1480          (if (eq byte-compile-warnings t)
1481              ;; XEmacs change
1482              (setq byte-compile-warnings byte-compile-default-warnings))
1483          (while (setq spec (cdr spec))
1484            (if (consp (car spec))
1485                (if (eq (cadar spec) 0)
1486                    (setq byte-compile-warnings
1487                          (delq (caar spec) byte-compile-warnings))
1488                  (setq byte-compile-warnings
1489                        (adjoin (caar spec) byte-compile-warnings)))))))
1490   nil)
1491
1492 ;;; Process any proclamations made before cl-macs was loaded.
1493 (defvar cl-proclaims-deferred)
1494 (let ((p (reverse cl-proclaims-deferred)))
1495   (while p (cl-do-proclaim (cl-pop p) t))
1496   (setq cl-proclaims-deferred nil))
1497
1498 ;;;###autoload
1499 (defmacro declare (&rest specs)
1500   (if (cl-compiling-file)
1501       (while specs
1502         (if (listp cl-declare-stack) (cl-push (car specs) cl-declare-stack))
1503         (cl-do-proclaim (cl-pop specs) nil)))
1504   nil)
1505
1506
1507
1508 ;;; Generalized variables.
1509
1510 ;;;###autoload
1511 (defmacro define-setf-method (func args &rest body)
1512   "(define-setf-method NAME ARGLIST BODY...): define a `setf' method.
1513 This method shows how to handle `setf's to places of the form (NAME ARGS...).
1514 The argument forms ARGS are bound according to ARGLIST, as if NAME were
1515 going to be expanded as a macro, then the BODY forms are executed and must
1516 return a list of five elements: a temporary-variables list, a value-forms
1517 list, a store-variables list (of length one), a store-form, and an access-
1518 form.  See `defsetf' for a simpler way to define most setf-methods."
1519   (append '(eval-when (compile load eval))
1520           (if (stringp (car body))
1521               (list (list 'put (list 'quote func) '(quote setf-documentation)
1522                           (cl-pop body))))
1523           (list (cl-transform-function-property
1524                  func 'setf-method (cons args body)))))
1525
1526 ;;;###autoload
1527 (defmacro defsetf (func arg1 &rest args)
1528   "(defsetf NAME FUNC): define a `setf' method.
1529 This macro is an easy-to-use substitute for `define-setf-method' that works
1530 well for simple place forms.  In the simple `defsetf' form, `setf's of
1531 the form (setf (NAME ARGS...) VAL) are transformed to function or macro
1532 calls of the form (FUNC ARGS... VAL).  Example: (defsetf aref aset).
1533 Alternate form: (defsetf NAME ARGLIST (STORE) BODY...).
1534 Here, the above `setf' call is expanded by binding the argument forms ARGS
1535 according to ARGLIST, binding the value form VAL to STORE, then executing
1536 BODY, which must return a Lisp form that does the necessary `setf' operation.
1537 Actually, ARGLIST and STORE may be bound to temporary variables which are
1538 introduced automatically to preserve proper execution order of the arguments.
1539 Example: (defsetf nth (n x) (v) (list 'setcar (list 'nthcdr n x) v))."
1540   (if (listp arg1)
1541       (let* ((largs nil) (largsr nil)
1542              (temps nil) (tempsr nil)
1543              (restarg nil) (rest-temps nil)
1544              (store-var (car (prog1 (car args) (setq args (cdr args)))))
1545              (store-temp (intern (format "--%s--temp--" store-var)))
1546              (lets1 nil) (lets2 nil)
1547              (docstr nil) (p arg1))
1548         (if (stringp (car args))
1549             (setq docstr (prog1 (car args) (setq args (cdr args)))))
1550         (while (and p (not (eq (car p) '&aux)))
1551           (if (eq (car p) '&rest)
1552               (setq p (cdr p) restarg (car p))
1553             (or (memq (car p) '(&optional &key &allow-other-keys))
1554                 (setq largs (cons (if (consp (car p)) (car (car p)) (car p))
1555                                   largs)
1556                       temps (cons (intern (format "--%s--temp--" (car largs)))
1557                                   temps))))
1558           (setq p (cdr p)))
1559         (setq largs (nreverse largs) temps (nreverse temps))
1560         (if restarg
1561             (setq largsr (append largs (list restarg))
1562                   rest-temps (intern (format "--%s--temp--" restarg))
1563                   tempsr (append temps (list rest-temps)))
1564           (setq largsr largs tempsr temps))
1565         (let ((p1 largs) (p2 temps))
1566           (while p1
1567             (setq lets1 (cons (list (car p2)
1568                                     (list 'gensym (format "--%s--" (car p1))))
1569                               lets1)
1570                   lets2 (cons (list (car p1) (car p2)) lets2)
1571                   p1 (cdr p1) p2 (cdr p2))))
1572         (if restarg (setq lets2 (cons (list restarg rest-temps) lets2)))
1573         (append (list 'define-setf-method func arg1)
1574                 (and docstr (list docstr))
1575                 (list
1576                  (list 'let*
1577                        (nreverse
1578                         (cons (list store-temp
1579                                     (list 'gensym (format "--%s--" store-var)))
1580                               (if restarg
1581                                   (append
1582                                    (list
1583                                     (list rest-temps
1584                                           (list 'mapcar '(quote gensym)
1585                                                 restarg)))
1586                                    lets1)
1587                                 lets1)))
1588                        (list 'list  ; 'values
1589                              (cons (if restarg 'list* 'list) tempsr)
1590                              (cons (if restarg 'list* 'list) largsr)
1591                              (list 'list store-temp)
1592                              (cons 'let*
1593                                    (cons (nreverse
1594                                           (cons (list store-var store-temp)
1595                                                 lets2))
1596                                          args))
1597                              (cons (if restarg 'list* 'list)
1598                                    (cons (list 'quote func) tempsr)))))))
1599     (list 'defsetf func '(&rest args) '(store)
1600           (let ((call (list 'cons (list 'quote arg1)
1601                             '(append args (list store)))))
1602             (if (car args)
1603                 (list 'list '(quote progn) call 'store)
1604               call)))))
1605
1606 ;;; Some standard place types from Common Lisp.
1607 (defsetf aref aset)
1608 (defsetf car setcar)
1609 (defsetf cdr setcdr)
1610 (defsetf elt (seq n) (store)
1611   (list 'if (list 'listp seq) (list 'setcar (list 'nthcdr n seq) store)
1612         (list 'aset seq n store)))
1613 (defsetf get (x y &optional d) (store) (list 'put x y store))
1614 (defsetf get* (x y &optional d) (store) (list 'put x y store))
1615 (defsetf gethash (x h &optional d) (store) (list 'cl-puthash x store h))
1616 (defsetf nth (n x) (store) (list 'setcar (list 'nthcdr n x) store))
1617 (defsetf subseq (seq start &optional end) (new)
1618   (list 'progn (list 'replace seq new ':start1 start ':end1 end) new))
1619 (defsetf symbol-function fset)
1620 (defsetf symbol-plist setplist)
1621 (defsetf symbol-value set)
1622
1623 ;;; Various car/cdr aliases.  Note that `cadr' is handled specially.
1624 (defsetf first setcar)
1625 (defsetf second (x) (store) (list 'setcar (list 'cdr x) store))
1626 (defsetf third (x) (store) (list 'setcar (list 'cddr x) store))
1627 (defsetf fourth (x) (store) (list 'setcar (list 'cdddr x) store))
1628 (defsetf fifth (x) (store) (list 'setcar (list 'nthcdr 4 x) store))
1629 (defsetf sixth (x) (store) (list 'setcar (list 'nthcdr 5 x) store))
1630 (defsetf seventh (x) (store) (list 'setcar (list 'nthcdr 6 x) store))
1631 (defsetf eighth (x) (store) (list 'setcar (list 'nthcdr 7 x) store))
1632 (defsetf ninth (x) (store) (list 'setcar (list 'nthcdr 8 x) store))
1633 (defsetf tenth (x) (store) (list 'setcar (list 'nthcdr 9 x) store))
1634 (defsetf rest setcdr)
1635
1636 ;;; Some more Emacs-related place types.
1637 (defsetf buffer-file-name set-visited-file-name t)
1638 (defsetf buffer-modified-p set-buffer-modified-p t)
1639 (defsetf buffer-name rename-buffer t)
1640 (defsetf buffer-string () (store)
1641   (list 'progn '(erase-buffer) (list 'insert store)))
1642 (defsetf buffer-substring cl-set-buffer-substring)
1643 (defsetf current-buffer set-buffer)
1644 (defsetf current-case-table set-case-table)
1645 (defsetf current-column move-to-column t)
1646 (defsetf current-global-map use-global-map t)
1647 (defsetf current-input-mode () (store)
1648   (list 'progn (list 'apply 'set-input-mode store) store))
1649 (defsetf current-local-map use-local-map t)
1650 (defsetf current-window-configuration set-window-configuration t)
1651 (defsetf default-file-modes set-default-file-modes t)
1652 (defsetf default-value set-default)
1653 (defsetf documentation-property put)
1654 (defsetf extent-face set-extent-face)
1655 (defsetf extent-priority set-extent-priority)
1656 (defsetf extent-property (x y &optional d) (arg)
1657   (list 'set-extent-property x y arg))
1658 (defsetf extent-end-position (ext) (store)
1659   (list 'progn (list 'set-extent-endpoints (list 'extent-start-position ext)
1660                      store) store))
1661 (defsetf extent-start-position (ext) (store)
1662   (list 'progn (list 'set-extent-endpoints store
1663                      (list 'extent-end-position ext)) store))
1664 (defsetf face-background (f &optional s) (x) (list 'set-face-background f x s))
1665 (defsetf face-background-pixmap (f &optional s) (x)
1666   (list 'set-face-background-pixmap f x s))
1667 (defsetf face-font (f &optional s) (x) (list 'set-face-font f x s))
1668 (defsetf face-foreground (f &optional s) (x) (list 'set-face-foreground f x s))
1669 (defsetf face-underline-p (f &optional s) (x)
1670   (list 'set-face-underline-p f x s))
1671 (defsetf file-modes set-file-modes t)
1672 (defsetf frame-parameters modify-frame-parameters t)
1673 (defsetf frame-visible-p cl-set-frame-visible-p)
1674 (defsetf frame-properties (&optional f) (p)
1675   `(progn (set-frame-properties ,f ,p) ,p))
1676 (defsetf frame-property (f p &optional d) (v)
1677   `(progn (set-frame-property ,f ,v) ,p))
1678 (defsetf frame-width (&optional f) (v)
1679   `(progn (set-frame-width ,f ,v) ,v))
1680 (defsetf frame-height (&optional f) (v)
1681   `(progn (set-frame-height ,f ,v) ,v))
1682 (defsetf current-frame-configuration set-frame-configuration)
1683
1684 ;; XEmacs: new stuff
1685 ;; Consoles
1686 (defsetf selected-console select-console t)
1687 (defsetf selected-device select-device t)
1688 (defsetf device-baud-rate (&optional d) (v)
1689   `(set-device-baud-rate ,d ,v))
1690 ;; This setf method is a bad idea, because set-specifier *adds* a
1691 ;; specification, rather than just setting it.  The net effect is that
1692 ;; it makes specifier-instance return VAL, but other things don't work
1693 ;; as expected -- letf, to name one.
1694 ;(defsetf specifier-instance (spec &optional dom def nof) (val)
1695 ;  `(set-specifier ,spec ,val ,dom))
1696
1697 ;; Annotations
1698 (defsetf annotation-glyph set-annotation-glyph)
1699 (defsetf annotation-down-glyph set-annotation-down-glyph)
1700 (defsetf annotation-face set-annotation-face)
1701 (defsetf annotation-layout set-annotation-layout)
1702 (defsetf annotation-data set-annotation-data)
1703 (defsetf annotation-action set-annotation-action)
1704 (defsetf annotation-menu set-annotation-menu)
1705 ;; Widget
1706 (defsetf widget-get widget-put t)
1707 (defsetf widget-value widget-value-set t)
1708
1709 ;; Misc
1710 (defsetf recent-keys-ring-size set-recent-keys-ring-size)
1711 (defsetf symbol-value-in-buffer (s b &optional u) (store)
1712   `(with-current-buffer ,b (set ,s ,store)))
1713 (defsetf symbol-value-in-console (s c &optional u) (store)
1714   `(letf (((selected-console) ,c))
1715      (set ,s ,store)))
1716
1717 (defsetf buffer-dedicated-frame (&optional b) (v)
1718   `(set-buffer-dedicated-frame ,b ,v))
1719 (defsetf console-type-image-conversion-list
1720   set-console-type-image-conversion-list)
1721 (defsetf default-toolbar-position set-default-toolbar-position)
1722 (defsetf device-class (&optional d) (v)
1723   `(set-device-class ,d ,v))
1724 (defsetf extent-begin-glyph set-extent-begin-glyph)
1725 (defsetf extent-begin-glyph-layout set-extent-begin-glyph-layout)
1726 (defsetf extent-end-glyph set-extent-end-glyph)
1727 (defsetf extent-end-glyph-layout set-extent-end-glyph-layout)
1728 (defsetf extent-keymap set-extent-keymap)
1729 (defsetf extent-parent set-extent-parent)
1730 (defsetf extent-properties set-extent-properties)
1731 ;; Avoid adding various face and glyph functions.
1732 (defsetf frame-selected-window (&optional f) (v)
1733   `(set-frame-selected-window ,f ,v))
1734 (defsetf itimer-function set-itimer-function)
1735 (defsetf itimer-function-arguments set-itimer-function-arguments)
1736 (defsetf itimer-is-idle set-itimer-is-idle)
1737 (defsetf itimer-recorded-run-time set-itimer-recorded-run-time)
1738 (defsetf itimer-restart set-itimer-restart)
1739 (defsetf itimer-uses-arguments set-itimer-uses-arguments)
1740 (defsetf itimer-value set-itimer-value)
1741 (defsetf keymap-parents set-keymap-parents)
1742 (defsetf marker-insertion-type set-marker-insertion-type)
1743 (defsetf mouse-pixel-position (&optional d) (v)
1744   `(progn
1745      set-mouse-pixel-position ,d ,(car v) ,(car (cdr v)) ,(cdr (cdr v))
1746      ,v))
1747 (defsetf trunc-stack-length set-trunc-stack-length)
1748 (defsetf trunc-stack-stack set-trunc-stack-stack)
1749 (defsetf undoable-stack-max set-undoable-stack-max)
1750 (defsetf weak-list-list set-weak-list-list)
1751
1752
1753 (defsetf getenv setenv t)
1754 (defsetf get-register set-register)
1755 (defsetf global-key-binding global-set-key)
1756 (defsetf keymap-parent set-keymap-parent)
1757 (defsetf keymap-name set-keymap-name)
1758 (defsetf keymap-prompt set-keymap-prompt)
1759 (defsetf keymap-default-binding set-keymap-default-binding)
1760 (defsetf local-key-binding local-set-key)
1761 (defsetf mark set-mark t)
1762 (defsetf mark-marker set-mark t)
1763 (defsetf marker-position set-marker t)
1764 (defsetf match-data store-match-data t)
1765 (defsetf mouse-position (scr) (store)
1766   (list 'set-mouse-position scr (list 'car store) (list 'cadr store)
1767         (list 'cddr store)))
1768 (defsetf overlay-get overlay-put)
1769 (defsetf overlay-start (ov) (store)
1770   (list 'progn (list 'move-overlay ov store (list 'overlay-end ov)) store))
1771 (defsetf overlay-end (ov) (store)
1772   (list 'progn (list 'move-overlay ov (list 'overlay-start ov) store) store))
1773 (defsetf point goto-char)
1774 (defsetf point-marker goto-char t)
1775 (defsetf point-max () (store)
1776   (list 'progn (list 'narrow-to-region '(point-min) store) store))
1777 (defsetf point-min () (store)
1778   (list 'progn (list 'narrow-to-region store '(point-max)) store))
1779 (defsetf process-buffer set-process-buffer)
1780 (defsetf process-filter set-process-filter)
1781 (defsetf process-sentinel set-process-sentinel)
1782 (defsetf read-mouse-position (scr) (store)
1783   (list 'set-mouse-position scr (list 'car store) (list 'cdr store)))
1784 (defsetf selected-window select-window)
1785 (defsetf selected-frame select-frame)
1786 (defsetf standard-case-table set-standard-case-table)
1787 (defsetf syntax-table set-syntax-table)
1788 (defsetf visited-file-modtime set-visited-file-modtime t)
1789 (defsetf window-buffer set-window-buffer t)
1790 (defsetf window-display-table set-window-display-table t)
1791 (defsetf window-dedicated-p set-window-dedicated-p t)
1792 (defsetf window-height () (store)
1793   (list 'progn (list 'enlarge-window (list '- store '(window-height))) store))
1794 (defsetf window-hscroll set-window-hscroll)
1795 (defsetf window-point set-window-point)
1796 (defsetf window-start set-window-start)
1797 (defsetf window-width () (store)
1798   (list 'progn (list 'enlarge-window (list '- store '(window-width)) t) store))
1799 (defsetf x-get-cutbuffer x-store-cutbuffer t)
1800 (defsetf x-get-cut-buffer x-store-cut-buffer t)   ; groan.
1801 (defsetf x-get-secondary-selection x-own-secondary-selection t)
1802 (defsetf x-get-selection x-own-selection t)
1803
1804 ;;; More complex setf-methods.
1805 ;;; These should take &environment arguments, but since full arglists aren't
1806 ;;; available while compiling cl-macs, we fake it by referring to the global
1807 ;;; variable cl-macro-environment directly.
1808
1809 (define-setf-method apply (func arg1 &rest rest)
1810   (or (and (memq (car-safe func) '(quote function function*))
1811            (symbolp (car-safe (cdr-safe func))))
1812       (error "First arg to apply in setf is not (function SYM): %s" func))
1813   (let* ((form (cons (nth 1 func) (cons arg1 rest)))
1814          (method (get-setf-method form cl-macro-environment)))
1815     (list (car method) (nth 1 method) (nth 2 method)
1816           (cl-setf-make-apply (nth 3 method) (cadr func) (car method))
1817           (cl-setf-make-apply (nth 4 method) (cadr func) (car method)))))
1818
1819 (defun cl-setf-make-apply (form func temps)
1820   (if (eq (car form) 'progn)
1821       (list* 'progn (cl-setf-make-apply (cadr form) func temps) (cddr form))
1822     (or (equal (last form) (last temps))
1823         (error "%s is not suitable for use with setf-of-apply" func))
1824     (list* 'apply (list 'quote (car form)) (cdr form))))
1825
1826 (define-setf-method nthcdr (n place)
1827   (let ((method (get-setf-method place cl-macro-environment))
1828         (n-temp (gensym "--nthcdr-n--"))
1829         (store-temp (gensym "--nthcdr-store--")))
1830     (list (cons n-temp (car method))
1831           (cons n (nth 1 method))
1832           (list store-temp)
1833           (list 'let (list (list (car (nth 2 method))
1834                                  (list 'cl-set-nthcdr n-temp (nth 4 method)
1835                                        store-temp)))
1836                 (nth 3 method) store-temp)
1837           (list 'nthcdr n-temp (nth 4 method)))))
1838
1839 (define-setf-method getf (place tag &optional def)
1840   (let ((method (get-setf-method place cl-macro-environment))
1841         (tag-temp (gensym "--getf-tag--"))
1842         (def-temp (gensym "--getf-def--"))
1843         (store-temp (gensym "--getf-store--")))
1844     (list (append (car method) (list tag-temp def-temp))
1845           (append (nth 1 method) (list tag def))
1846           (list store-temp)
1847           (list 'let (list (list (car (nth 2 method))
1848                                  (list 'cl-set-getf (nth 4 method)
1849                                        tag-temp store-temp)))
1850                 (nth 3 method) store-temp)
1851           (list 'getf (nth 4 method) tag-temp def-temp))))
1852
1853 (define-setf-method substring (place from &optional to)
1854   (let ((method (get-setf-method place cl-macro-environment))
1855         (from-temp (gensym "--substring-from--"))
1856         (to-temp (gensym "--substring-to--"))
1857         (store-temp (gensym "--substring-store--")))
1858     (list (append (car method) (list from-temp to-temp))
1859           (append (nth 1 method) (list from to))
1860           (list store-temp)
1861           (list 'let (list (list (car (nth 2 method))
1862                                  (list 'cl-set-substring (nth 4 method)
1863                                        from-temp to-temp store-temp)))
1864                 (nth 3 method) store-temp)
1865           (list 'substring (nth 4 method) from-temp to-temp))))
1866
1867 (define-setf-method values (&rest args)
1868   (let ((methods (mapcar #'(lambda (x)
1869                              (get-setf-method x cl-macro-environment))
1870                          args))
1871         (store-temp (gensym "--values-store--")))
1872     (list (apply 'append (mapcar 'first methods))
1873           (apply 'append (mapcar 'second methods))
1874           (list store-temp)
1875           (cons 'list
1876                 (mapcar #'(lambda (m)
1877                             (cl-setf-do-store (cons (car (third m)) (fourth m))
1878                                               (list 'pop store-temp)))
1879                         methods))
1880           (cons 'list (mapcar 'fifth methods)))))
1881
1882 ;;; Getting and optimizing setf-methods.
1883 ;;;###autoload
1884 (defun get-setf-method (place &optional env)
1885   "Return a list of five values describing the setf-method for PLACE.
1886 PLACE may be any Lisp form which can appear as the PLACE argument to
1887 a macro like `setf' or `incf'."
1888   (if (symbolp place)
1889       (let ((temp (gensym "--setf--")))
1890         (list nil nil (list temp) (list 'setq place temp) place))
1891     (or (and (symbolp (car place))
1892              (let* ((func (car place))
1893                     (name (symbol-name func))
1894                     (method (get func 'setf-method))
1895                     (case-fold-search nil))
1896                (or (and method
1897                         (let ((cl-macro-environment env))
1898                           (setq method (apply method (cdr place))))
1899                         (if (and (consp method) (= (length method) 5))
1900                             method
1901                           (error "Setf-method for %s returns malformed method"
1902                                  func)))
1903                    (and (save-match-data
1904                           (string-match "\\`c[ad][ad][ad]?[ad]?r\\'" name))
1905                         (get-setf-method (compiler-macroexpand place)))
1906                    (and (eq func 'edebug-after)
1907                         (get-setf-method (nth (1- (length place)) place)
1908                                          env)))))
1909         (if (eq place (setq place (macroexpand place env)))
1910             (if (and (symbolp (car place)) (fboundp (car place))
1911                      (symbolp (symbol-function (car place))))
1912                 (get-setf-method (cons (symbol-function (car place))
1913                                        (cdr place)) env)
1914               (error "No setf-method known for %s" (car place)))
1915           (get-setf-method place env)))))
1916
1917 (defun cl-setf-do-modify (place opt-expr)
1918   (let* ((method (get-setf-method place cl-macro-environment))
1919          (temps (car method)) (values (nth 1 method))
1920          (lets nil) (subs nil)
1921          (optimize (and (not (eq opt-expr 'no-opt))
1922                         (or (and (not (eq opt-expr 'unsafe))
1923                                  (cl-safe-expr-p opt-expr))
1924                             (cl-setf-simple-store-p (car (nth 2 method))
1925                                                     (nth 3 method)))))
1926          (simple (and optimize (consp place) (cl-simple-exprs-p (cdr place)))))
1927     (while values
1928       (if (or simple (cl-const-expr-p (car values)))
1929           (cl-push (cons (cl-pop temps) (cl-pop values)) subs)
1930         (cl-push (list (cl-pop temps) (cl-pop values)) lets)))
1931     (list (nreverse lets)
1932           (cons (car (nth 2 method)) (sublis subs (nth 3 method)))
1933           (sublis subs (nth 4 method)))))
1934
1935 (defun cl-setf-do-store (spec val)
1936   (let ((sym (car spec))
1937         (form (cdr spec)))
1938     (if (or (cl-const-expr-p val)
1939             (and (cl-simple-expr-p val) (eq (cl-expr-contains form sym) 1))
1940             (cl-setf-simple-store-p sym form))
1941         (subst val sym form)
1942       (list 'let (list (list sym val)) form))))
1943
1944 (defun cl-setf-simple-store-p (sym form)
1945   (and (consp form) (eq (cl-expr-contains form sym) 1)
1946        (eq (nth (1- (length form)) form) sym)
1947        (symbolp (car form)) (fboundp (car form))
1948        (not (eq (car-safe (symbol-function (car form))) 'macro))))
1949
1950 ;;; The standard modify macros.
1951 ;;;###autoload
1952 (defmacro setf (&rest args)
1953   "(setf PLACE VAL PLACE VAL ...): set each PLACE to the value of its VAL.
1954 This is a generalized version of `setq'; the PLACEs may be symbolic
1955 references such as (car x) or (aref x i), as well as plain symbols.
1956 For example, (setf (cadar x) y) is equivalent to (setcar (cdar x) y).
1957 The return value is the last VAL in the list."
1958   (if (cdr (cdr args))
1959       (let ((sets nil))
1960         (while args (cl-push (list 'setf (cl-pop args) (cl-pop args)) sets))
1961         (cons 'progn (nreverse sets)))
1962     (if (symbolp (car args))
1963         (and args (cons 'setq args))
1964       (let* ((method (cl-setf-do-modify (car args) (nth 1 args)))
1965              (store (cl-setf-do-store (nth 1 method) (nth 1 args))))
1966         (if (car method) (list 'let* (car method) store) store)))))
1967
1968 ;;;###autoload
1969 (defmacro psetf (&rest args)
1970   "(psetf PLACE VAL PLACE VAL ...): set PLACEs to the values VALs in parallel.
1971 This is like `setf', except that all VAL forms are evaluated (in order)
1972 before assigning any PLACEs to the corresponding values."
1973   (let ((p args) (simple t) (vars nil))
1974     (while p
1975       (if (or (not (symbolp (car p))) (cl-expr-depends-p (nth 1 p) vars))
1976           (setq simple nil))
1977       (if (memq (car p) vars)
1978           (error "Destination duplicated in psetf: %s" (car p)))
1979       (cl-push (cl-pop p) vars)
1980       (or p (error "Odd number of arguments to psetf"))
1981       (cl-pop p))
1982     (if simple
1983         (list 'progn (cons 'setf args) nil)
1984       (setq args (reverse args))
1985       (let ((expr (list 'setf (cadr args) (car args))))
1986         (while (setq args (cddr args))
1987           (setq expr (list 'setf (cadr args) (list 'prog1 (car args) expr))))
1988         (list 'progn expr nil)))))
1989
1990 ;;;###autoload
1991 (defun cl-do-pop (place)
1992   (if (cl-simple-expr-p place)
1993       (list 'prog1 (list 'car place) (list 'setf place (list 'cdr place)))
1994     (let* ((method (cl-setf-do-modify place t))
1995            (temp (gensym "--pop--")))
1996       (list 'let*
1997             (append (car method)
1998                     (list (list temp (nth 2 method))))
1999             (list 'prog1
2000                   (list 'car temp)
2001                   (cl-setf-do-store (nth 1 method) (list 'cdr temp)))))))
2002
2003 ;;;###autoload
2004 (defmacro remf (place tag)
2005   "(remf PLACE TAG): remove TAG from property list PLACE.
2006 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2007 The form returns true if TAG was found and removed, nil otherwise."
2008   (let* ((method (cl-setf-do-modify place t))
2009          (tag-temp (and (not (cl-const-expr-p tag)) (gensym "--remf-tag--")))
2010          (val-temp (and (not (cl-simple-expr-p place))
2011                         (gensym "--remf-place--")))
2012          (ttag (or tag-temp tag))
2013          (tval (or val-temp (nth 2 method))))
2014     (list 'let*
2015           (append (car method)
2016                   (and val-temp (list (list val-temp (nth 2 method))))
2017                   (and tag-temp (list (list tag-temp tag))))
2018           (list 'if (list 'eq ttag (list 'car tval))
2019                 (list 'progn
2020                       (cl-setf-do-store (nth 1 method) (list 'cddr tval))
2021                       t)
2022                 (list 'cl-do-remf tval ttag)))))
2023
2024 ;;;###autoload
2025 (defmacro shiftf (place &rest args)
2026   "(shiftf PLACE PLACE... VAL): shift left among PLACEs.
2027 Example: (shiftf A B C) sets A to B, B to C, and returns the old A.
2028 Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
2029   (if (not (memq nil (mapcar 'symbolp (butlast (cons place args)))))
2030       (list* 'prog1 place
2031              (let ((sets nil))
2032                (while args
2033                  (cl-push (list 'setq place (car args)) sets)
2034                  (setq place (cl-pop args)))
2035                (nreverse sets)))
2036     (let* ((places (reverse (cons place args)))
2037            (form (cl-pop places)))
2038       (while places
2039         (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
2040           (setq form (list 'let* (car method)
2041                            (list 'prog1 (nth 2 method)
2042                                  (cl-setf-do-store (nth 1 method) form))))))
2043       form)))
2044
2045 ;;;###autoload
2046 (defmacro rotatef (&rest args)
2047   "(rotatef PLACE...): rotate left among PLACEs.
2048 Example: (rotatef A B C) sets A to B, B to C, and C to A.  It returns nil.
2049 Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
2050   (if (not (memq nil (mapcar 'symbolp args)))
2051       (and (cdr args)
2052            (let ((sets nil)
2053                  (first (car args)))
2054              (while (cdr args)
2055                (setq sets (nconc sets (list (cl-pop args) (car args)))))
2056              (nconc (list 'psetf) sets (list (car args) first))))
2057     (let* ((places (reverse args))
2058            (temp (gensym "--rotatef--"))
2059            (form temp))
2060       (while (cdr places)
2061         (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
2062           (setq form (list 'let* (car method)
2063                            (list 'prog1 (nth 2 method)
2064                                  (cl-setf-do-store (nth 1 method) form))))))
2065       (let ((method (cl-setf-do-modify (car places) 'unsafe)))
2066         (list 'let* (append (car method) (list (list temp (nth 2 method))))
2067               (cl-setf-do-store (nth 1 method) form) nil)))))
2068
2069 ;;;###autoload
2070 (defmacro letf (bindings &rest body)
2071   "(letf ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
2072 This is the analogue of `let', but with generalized variables (in the
2073 sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
2074 VALUE, then the BODY forms are executed.  On exit, either normally or
2075 because of a `throw' or error, the PLACEs are set back to their original
2076 values.  Note that this macro is *not* available in Common Lisp.
2077 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2078 the PLACE is not modified before executing BODY."
2079   (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2080       (list* 'let bindings body)
2081     (let ((lets nil) (sets nil)
2082           (unsets nil) (rev (reverse bindings)))
2083       (while rev
2084         (let* ((place (if (symbolp (caar rev))
2085                           (list 'symbol-value (list 'quote (caar rev)))
2086                         (caar rev)))
2087                (value (cadar rev))
2088                (method (cl-setf-do-modify place 'no-opt))
2089                (save (gensym "--letf-save--"))
2090                (bound (and (memq (car place) '(symbol-value symbol-function))
2091                            (gensym "--letf-bound--")))
2092                (temp (and (not (cl-const-expr-p value)) (cdr bindings)
2093                           (gensym "--letf-val--"))))
2094           (setq lets (nconc (car method)
2095                             (if bound
2096                                 (list (list bound
2097                                             (list (if (eq (car place)
2098                                                           'symbol-value)
2099                                                       'boundp 'fboundp)
2100                                                   (nth 1 (nth 2 method))))
2101                                       (list save (list 'and bound
2102                                                        (nth 2 method))))
2103                               (list (list save (nth 2 method))))
2104                             (and temp (list (list temp value)))
2105                             lets)
2106                 body (list
2107                       (list 'unwind-protect
2108                             (cons 'progn
2109                                   (if (cdr (car rev))
2110                                       (cons (cl-setf-do-store (nth 1 method)
2111                                                               (or temp value))
2112                                             body)
2113                                     body))
2114                             (if bound
2115                                 (list 'if bound
2116                                       (cl-setf-do-store (nth 1 method) save)
2117                                       (list (if (eq (car place) 'symbol-value)
2118                                                 'makunbound 'fmakunbound)
2119                                             (nth 1 (nth 2 method))))
2120                               (cl-setf-do-store (nth 1 method) save))))
2121                 rev (cdr rev))))
2122       (list* 'let* lets body))))
2123
2124 ;;;###autoload
2125 (defmacro letf* (bindings &rest body)
2126   "(letf* ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
2127 This is the analogue of `let*', but with generalized variables (in the
2128 sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
2129 VALUE, then the BODY forms are executed.  On exit, either normally or
2130 because of a `throw' or error, the PLACEs are set back to their original
2131 values.  Note that this macro is *not* available in Common Lisp.
2132 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2133 the PLACE is not modified before executing BODY."
2134   (if (null bindings)
2135       (cons 'progn body)
2136     (setq bindings (reverse bindings))
2137     (while bindings
2138       (setq body (list (list* 'letf (list (cl-pop bindings)) body))))
2139     (car body)))
2140
2141 ;;;###autoload
2142 (defmacro callf (func place &rest args)
2143   "(callf FUNC PLACE ARGS...): set PLACE to (FUNC PLACE ARGS...).
2144 FUNC should be an unquoted function name.  PLACE may be a symbol,
2145 or any generalized variable allowed by `setf'."
2146   (let* ((method (cl-setf-do-modify place (cons 'list args)))
2147          (rargs (cons (nth 2 method) args)))
2148     (list 'let* (car method)
2149           (cl-setf-do-store (nth 1 method)
2150                             (if (symbolp func) (cons func rargs)
2151                               (list* 'funcall (list 'function func)
2152                                      rargs))))))
2153
2154 ;;;###autoload
2155 (defmacro callf2 (func arg1 place &rest args)
2156   "(callf2 FUNC ARG1 PLACE ARGS...): set PLACE to (FUNC ARG1 PLACE ARGS...).
2157 Like `callf', but PLACE is the second argument of FUNC, not the first."
2158   (if (and (cl-safe-expr-p arg1) (cl-simple-expr-p place) (symbolp func))
2159       (list 'setf place (list* func arg1 place args))
2160     (let* ((method (cl-setf-do-modify place (cons 'list args)))
2161            (temp (and (not (cl-const-expr-p arg1)) (gensym "--arg1--")))
2162            (rargs (list* (or temp arg1) (nth 2 method) args)))
2163       (list 'let* (append (and temp (list (list temp arg1))) (car method))
2164             (cl-setf-do-store (nth 1 method)
2165                               (if (symbolp func) (cons func rargs)
2166                                 (list* 'funcall (list 'function func)
2167                                        rargs)))))))
2168
2169 ;;;###autoload
2170 (defmacro define-modify-macro (name arglist func &optional doc)
2171   "(define-modify-macro NAME ARGLIST FUNC): define a `setf'-like modify macro.
2172 If NAME is called, it combines its PLACE argument with the other arguments
2173 from ARGLIST using FUNC: (define-modify-macro incf (&optional (n 1)) +)"
2174   (if (memq '&key arglist) (error "&key not allowed in define-modify-macro"))
2175   (let ((place (gensym "--place--")))
2176     (list 'defmacro* name (cons place arglist) doc
2177           (list* (if (memq '&rest arglist) 'list* 'list)
2178                  '(quote callf) (list 'quote func) place
2179                  (cl-arglist-args arglist)))))
2180
2181
2182 ;;; Structures.
2183
2184 ;;;###autoload
2185 (defmacro defstruct (struct &rest descs)
2186   "(defstruct (NAME OPTIONS...) (SLOT SLOT-OPTS...)...): define a struct type.
2187 This macro defines a new Lisp data type called NAME, which contains data
2188 stored in SLOTs.  This defines a `make-NAME' constructor, a `copy-NAME'
2189 copier, a `NAME-p' predicate, and setf-able `NAME-SLOT' accessors."
2190   (let* ((name (if (consp struct) (car struct) struct))
2191          (opts (cdr-safe struct))
2192          (slots nil)
2193          (defaults nil)
2194          (conc-name (concat (symbol-name name) "-"))
2195          (constructor (intern (format "make-%s" name)))
2196          (constrs nil)
2197          (copier (intern (format "copy-%s" name)))
2198          (predicate (intern (format "%s-p" name)))
2199          (print-func nil) (print-auto nil)
2200          (safety (if (cl-compiling-file) cl-optimize-safety 3))
2201          (include nil)
2202          (tag (intern (format "cl-struct-%s" name)))
2203          (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2204          (include-descs nil)
2205          ;; XEmacs change
2206          (include-tag-symbol nil)
2207          (side-eff nil)
2208          (type nil)
2209          (named nil)
2210          (forms nil)
2211          pred-form pred-check)
2212     (if (stringp (car descs))
2213         (cl-push (list 'put (list 'quote name) '(quote structure-documentation)
2214                        (cl-pop descs)) forms))
2215     (setq descs (cons '(cl-tag-slot)
2216                       (mapcar (function (lambda (x) (if (consp x) x (list x))))
2217                               descs)))
2218     (while opts
2219       (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2220             (args (cdr-safe (cl-pop opts))))
2221         (cond ((eq opt ':conc-name)
2222                (if args
2223                    (setq conc-name (if (car args)
2224                                        (symbol-name (car args)) ""))))
2225               ((eq opt ':constructor)
2226                (if (cdr args)
2227                    (cl-push args constrs)
2228                  (if args (setq constructor (car args)))))
2229               ((eq opt ':copier)
2230                (if args (setq copier (car args))))
2231               ((eq opt ':predicate)
2232                (if args (setq predicate (car args))))
2233               ((eq opt ':include)
2234                (setq include (car args)
2235                      include-descs (mapcar (function
2236                                             (lambda (x)
2237                                               (if (consp x) x (list x))))
2238                                            (cdr args))
2239                      ;; XEmacs change
2240                      include-tag-symbol (intern (format "cl-struct-%s-tags"
2241                                                         include))))
2242               ((eq opt ':print-function)
2243                (setq print-func (car args)))
2244               ((eq opt ':type)
2245                (setq type (car args)))
2246               ((eq opt ':named)
2247                (setq named t))
2248               ((eq opt ':initial-offset)
2249                (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2250                                   descs)))
2251               (t
2252                (error "Slot option %s unrecognized" opt)))))
2253     (if print-func
2254         (setq print-func (list 'progn
2255                                (list 'funcall (list 'function print-func)
2256                                      'cl-x 'cl-s 'cl-n) t))
2257       (or type (and include (not (get include 'cl-struct-print)))
2258           (setq print-auto t
2259                 print-func (and (or (not (or include type)) (null print-func))
2260                                 (list 'progn
2261                                       (list 'princ (format "#S(%s" name)
2262                                             'cl-s))))))
2263     (if include
2264         (let ((inc-type (get include 'cl-struct-type))
2265               (old-descs (get include 'cl-struct-slots)))
2266           (or inc-type (error "%s is not a struct name" include))
2267           (and type (not (eq (car inc-type) type))
2268                (error ":type disagrees with :include for %s" name))
2269           (while include-descs
2270             (setcar (memq (or (assq (caar include-descs) old-descs)
2271                               (error "No slot %s in included struct %s"
2272                                      (caar include-descs) include))
2273                           old-descs)
2274                     (cl-pop include-descs)))
2275           (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2276                 type (car inc-type)
2277                 named (assq 'cl-tag-slot descs))
2278           (if (cadr inc-type) (setq tag name named t))
2279           (let ((incl include))
2280             (while incl
2281               (cl-push (list 'pushnew (list 'quote tag)
2282                              (intern (format "cl-struct-%s-tags" incl)))
2283                        forms)
2284               (setq incl (get incl 'cl-struct-include)))))
2285       (if type
2286           (progn
2287             (or (memq type '(vector list))
2288                 (error "Illegal :type specifier: %s" type))
2289             (if named (setq tag name)))
2290         (setq type 'vector named 'true)))
2291     (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2292     (cl-push (list 'defvar tag-symbol) forms)
2293     (setq pred-form (and named
2294                          (let ((pos (- (length descs)
2295                                        (length (memq (assq 'cl-tag-slot descs)
2296                                                      descs)))))
2297                            (if (eq type 'vector)
2298                                (list 'and '(vectorp cl-x)
2299                                      (list '>= '(length cl-x) (length descs))
2300                                      (list 'memq (list 'aref 'cl-x pos)
2301                                            tag-symbol))
2302                              (if (= pos 0)
2303                                  (list 'memq '(car-safe cl-x) tag-symbol)
2304                                (list 'and '(consp cl-x)
2305                                      (list 'memq (list 'nth pos 'cl-x)
2306                                            tag-symbol))))))
2307           pred-check (and pred-form (> safety 0)
2308                           (if (and (eq (caadr pred-form) 'vectorp)
2309                                    (= safety 1))
2310                               (cons 'and (cdddr pred-form)) pred-form)))
2311     (let ((pos 0) (descp descs))
2312       (while descp
2313         (let* ((desc (cl-pop descp))
2314                (slot (car desc)))
2315           (if (memq slot '(cl-tag-slot cl-skip-slot))
2316               (progn
2317                 (cl-push nil slots)
2318                 (cl-push (and (eq slot 'cl-tag-slot) (list 'quote tag))
2319                          defaults))
2320             (if (assq slot descp)
2321                 (error "Duplicate slots named %s in %s" slot name))
2322             (let ((accessor (intern (format "%s%s" conc-name slot))))
2323               (cl-push slot slots)
2324               (cl-push (nth 1 desc) defaults)
2325               (cl-push (list*
2326                         'defsubst* accessor '(cl-x)
2327                         (append
2328                          (and pred-check
2329                               (list (list 'or pred-check
2330                                           (list 'error
2331                                                 (format "%s accessing a non-%s"
2332                                                         accessor name)
2333                                                 'cl-x))))
2334                          (list (if (eq type 'vector) (list 'aref 'cl-x pos)
2335                                  (if (= pos 0) '(car cl-x)
2336                                    (list 'nth pos 'cl-x)))))) forms)
2337               (cl-push (cons accessor t) side-eff)
2338               (cl-push (list 'define-setf-method accessor '(cl-x)
2339                              (if (cadr (memq ':read-only (cddr desc)))
2340                                  (list 'error (format "%s is a read-only slot"
2341                                                       accessor))
2342                                (list 'cl-struct-setf-expander 'cl-x
2343                                      (list 'quote name) (list 'quote accessor)
2344                                      (and pred-check (list 'quote pred-check))
2345                                      pos)))
2346                        forms)
2347               (if print-auto
2348                   (nconc print-func
2349                          (list (list 'princ (format " %s" slot) 'cl-s)
2350                                (list 'prin1 (list accessor 'cl-x) 'cl-s)))))))
2351         (setq pos (1+ pos))))
2352     (setq slots (nreverse slots)
2353           defaults (nreverse defaults))
2354     (and predicate pred-form
2355          (progn (cl-push (list 'defsubst* predicate '(cl-x)
2356                                (if (eq (car pred-form) 'and)
2357                                    (append pred-form '(t))
2358                                  (list 'and pred-form t))) forms)
2359                 (cl-push (cons predicate 'error-free) side-eff)))
2360     (and copier
2361          (progn (cl-push (list 'defun copier '(x) '(copy-sequence x)) forms)
2362                 (cl-push (cons copier t) side-eff)))
2363     (if constructor
2364         (cl-push (list constructor
2365                        (cons '&key (delq nil (copy-sequence slots))))
2366                  constrs))
2367     (while constrs
2368       (let* ((name (caar constrs))
2369              (args (cadr (cl-pop constrs)))
2370              (anames (cl-arglist-args args))
2371              (make (mapcar* (function (lambda (s d) (if (memq s anames) s d)))
2372                             slots defaults)))
2373         (cl-push (list 'defsubst* name
2374                        (list* '&cl-defs (list 'quote (cons nil descs)) args)
2375                        (cons type make)) forms)
2376         (if (cl-safe-expr-p (cons 'progn (mapcar 'second descs)))
2377             (cl-push (cons name t) side-eff))))
2378     (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2379     (if print-func
2380         (cl-push (list 'push
2381                        (list 'function
2382                              (list 'lambda '(cl-x cl-s cl-n)
2383                                    (list 'and pred-form print-func)))
2384                        'custom-print-functions) forms))
2385     (cl-push (list 'setq tag-symbol (list 'list (list 'quote tag))) forms)
2386     (cl-push (list* 'eval-when '(compile load eval)
2387                     (list 'put (list 'quote name) '(quote cl-struct-slots)
2388                           (list 'quote descs))
2389                     (list 'put (list 'quote name) '(quote cl-struct-type)
2390                           (list 'quote (list type (eq named t))))
2391                     (list 'put (list 'quote name) '(quote cl-struct-include)
2392                           (list 'quote include))
2393                     (list 'put (list 'quote name) '(quote cl-struct-print)
2394                           print-auto)
2395                     (mapcar (function (lambda (x)
2396                                         (list 'put (list 'quote (car x))
2397                                               '(quote side-effect-free)
2398                                               (list 'quote (cdr x)))))
2399                             side-eff))
2400              forms)
2401     (cons 'progn (nreverse (cons (list 'quote name) forms)))))
2402
2403 ;;;###autoload
2404 (defun cl-struct-setf-expander (x name accessor pred-form pos)
2405   (let* ((temp (gensym "--x--")) (store (gensym "--store--")))
2406     (list (list temp) (list x) (list store)
2407           (append '(progn)
2408                   (and pred-form
2409                        (list (list 'or (subst temp 'cl-x pred-form)
2410                                    (list 'error
2411                                          (format
2412                                           "%s storing a non-%s" accessor name)
2413                                          temp))))
2414                   (list (if (eq (car (get name 'cl-struct-type)) 'vector)
2415                             (list 'aset temp pos store)
2416                           (list 'setcar
2417                                 (if (<= pos 5)
2418                                     (let ((xx temp))
2419                                       (while (>= (setq pos (1- pos)) 0)
2420                                         (setq xx (list 'cdr xx)))
2421                                       xx)
2422                                   (list 'nthcdr pos temp))
2423                                 store))))
2424           (list accessor temp))))
2425
2426
2427 ;;; Types and assertions.
2428
2429 ;;;###autoload
2430 (defmacro deftype (name args &rest body)
2431   "(deftype NAME ARGLIST BODY...): define NAME as a new data type.
2432 The type name can then be used in `typecase', `check-type', etc."
2433   (list 'eval-when '(compile load eval)
2434         (cl-transform-function-property
2435          name 'cl-deftype-handler (cons (list* '&cl-defs ''('*) args) body))))
2436
2437 (defun cl-make-type-test (val type)
2438   (if (symbolp type)
2439       (cond ((get type 'cl-deftype-handler)
2440              (cl-make-type-test val (funcall (get type 'cl-deftype-handler))))
2441             ((memq type '(nil t)) type)
2442             ((eq type 'string-char) (list 'characterp val))
2443             ((eq type 'null) (list 'null val))
2444             ((eq type 'float) (list 'floatp-safe val))
2445             ((eq type 'real) (list 'numberp val))
2446             ((eq type 'fixnum) (list 'integerp val))
2447             (t
2448              (let* ((name (symbol-name type))
2449                     (namep (intern (concat name "p"))))
2450                (if (fboundp namep) (list namep val)
2451                  (list (intern (concat name "-p")) val)))))
2452     (cond ((get (car type) 'cl-deftype-handler)
2453            (cl-make-type-test val (apply (get (car type) 'cl-deftype-handler)
2454                                          (cdr type))))
2455           ((memq (car-safe type) '(integer float real number))
2456            (delq t (list 'and (cl-make-type-test val (car type))
2457                          (if (memq (cadr type) '(* nil)) t
2458                            (if (consp (cadr type)) (list '> val (caadr type))
2459                              (list '>= val (cadr type))))
2460                          (if (memq (caddr type) '(* nil)) t
2461                            (if (consp (caddr type)) (list '< val (caaddr type))
2462                              (list '<= val (caddr type)))))))
2463           ((memq (car-safe type) '(and or not))
2464            (cons (car type)
2465                  (mapcar (function (lambda (x) (cl-make-type-test val x)))
2466                          (cdr type))))
2467           ((memq (car-safe type) '(member member*))
2468            (list 'and (list 'member* val (list 'quote (cdr type))) t))
2469           ((eq (car-safe type) 'satisfies) (list (cadr type) val))
2470           (t (error "Bad type spec: %s" type)))))
2471
2472 ;;;###autoload
2473 (defun typep (val type)   ; See compiler macro below.
2474   "Check that OBJECT is of type TYPE.
2475 TYPE is a Common Lisp-style type specifier."
2476   (eval (cl-make-type-test 'val type)))
2477
2478 ;;;###autoload
2479 (defmacro check-type (form type &optional string)
2480   "Verify that FORM is of type TYPE; signal an error if not.
2481 STRING is an optional description of the desired type."
2482   (and (or (not (cl-compiling-file))
2483            (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2484        (let* ((temp (if (cl-simple-expr-p form 3) form (gensym)))
2485               (body (list 'or (cl-make-type-test temp type)
2486                           (list 'signal '(quote wrong-type-argument)
2487                                 (list 'list (or string (list 'quote type))
2488                                       temp (list 'quote form))))))
2489          (if (eq temp form) (list 'progn body nil)
2490            (list 'let (list (list temp form)) body nil)))))
2491
2492 ;;;###autoload
2493 (defmacro assert (form &optional show-args string &rest args)
2494   "Verify that FORM returns non-nil; signal an error if not.
2495 Second arg SHOW-ARGS means to include arguments of FORM in message.
2496 Other args STRING and ARGS... are arguments to be passed to `error'.
2497 They are not evaluated unless the assertion fails.  If STRING is
2498 omitted, a default message listing FORM itself is used."
2499   (and (or (not (cl-compiling-file))
2500            (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2501        (let ((sargs (and show-args (delq nil (mapcar
2502                                               (function
2503                                                (lambda (x)
2504                                                  (and (not (cl-const-expr-p x))
2505                                                       x))) (cdr form))))))
2506          (list 'progn
2507                (list 'or form
2508                      (if string
2509                          (list* 'error string (append sargs args))
2510                        (list 'signal '(quote cl-assertion-failed)
2511                              (list* 'list (list 'quote form) sargs))))
2512                nil))))
2513
2514 ;;;###autoload
2515 (defmacro ignore-errors (&rest body)
2516   "Execute FORMS; if an error occurs, return nil.
2517 Otherwise, return result of last FORM."
2518   (list 'condition-case nil (cons 'progn body) '(error nil)))
2519
2520
2521 ;;; Some predicates for analyzing Lisp forms.  These are used by various
2522 ;;; macro expanders to optimize the results in certain common cases.
2523
2524 (defconst cl-simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
2525                             car-safe cdr-safe progn prog1 prog2))
2526 (defconst cl-safe-funcs '(* / % length memq list vector vectorp
2527                           < > <= >= = error))
2528
2529 ;;; Check if no side effects, and executes quickly.
2530 (defun cl-simple-expr-p (x &optional size)
2531   (or size (setq size 10))
2532   (if (and (consp x) (not (memq (car x) '(quote function function*))))
2533       (and (symbolp (car x))
2534            (or (memq (car x) cl-simple-funcs)
2535                (get (car x) 'side-effect-free))
2536            (progn
2537              (setq size (1- size))
2538              (while (and (setq x (cdr x))
2539                          (setq size (cl-simple-expr-p (car x) size))))
2540              (and (null x) (>= size 0) size)))
2541     (and (> size 0) (1- size))))
2542
2543 (defun cl-simple-exprs-p (xs)
2544   (while (and xs (cl-simple-expr-p (car xs)))
2545     (setq xs (cdr xs)))
2546   (not xs))
2547
2548 ;;; Check if no side effects.
2549 (defun cl-safe-expr-p (x)
2550   (or (not (and (consp x) (not (memq (car x) '(quote function function*)))))
2551       (and (symbolp (car x))
2552            (or (memq (car x) cl-simple-funcs)
2553                (memq (car x) cl-safe-funcs)
2554                (get (car x) 'side-effect-free))
2555            (progn
2556              (while (and (setq x (cdr x)) (cl-safe-expr-p (car x))))
2557              (null x)))))
2558
2559 ;;; Check if constant (i.e., no side effects or dependencies).
2560 (defun cl-const-expr-p (x)
2561   (cond ((consp x)
2562          (or (eq (car x) 'quote)
2563              (and (memq (car x) '(function function*))
2564                   (or (symbolp (nth 1 x))
2565                       (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
2566         ((symbolp x) (and (memq x '(nil t)) t))
2567         (t t)))
2568
2569 (defun cl-const-exprs-p (xs)
2570   (while (and xs (cl-const-expr-p (car xs)))
2571     (setq xs (cdr xs)))
2572   (not xs))
2573
2574 (defun cl-const-expr-val (x)
2575   (and (eq (cl-const-expr-p x) t) (if (consp x) (nth 1 x) x)))
2576
2577 (defun cl-expr-access-order (x v)
2578   (if (cl-const-expr-p x) v
2579     (if (consp x)
2580         (progn
2581           (while (setq x (cdr x)) (setq v (cl-expr-access-order (car x) v)))
2582           v)
2583       (if (eq x (car v)) (cdr v) '(t)))))
2584
2585 ;;; Count number of times X refers to Y.  Return NIL for 0 times.
2586 (defun cl-expr-contains (x y)
2587   (cond ((equal y x) 1)
2588         ((and (consp x) (not (memq (car-safe x) '(quote function function*))))
2589          (let ((sum 0))
2590            (while x
2591              (setq sum (+ sum (or (cl-expr-contains (cl-pop x) y) 0))))
2592            (and (> sum 0) sum)))
2593         (t nil)))
2594
2595 (defun cl-expr-contains-any (x y)
2596   (while (and y (not (cl-expr-contains x (car y)))) (cl-pop y))
2597   y)
2598
2599 ;;; Check whether X may depend on any of the symbols in Y.
2600 (defun cl-expr-depends-p (x y)
2601   (and (not (cl-const-expr-p x))
2602        (or (not (cl-safe-expr-p x)) (cl-expr-contains-any x y))))
2603
2604
2605 ;;; Compiler macros.
2606
2607 ;;;###autoload
2608 (defmacro define-compiler-macro (func args &rest body)
2609   "(define-compiler-macro FUNC ARGLIST BODY...): Define a compiler-only macro.
2610 This is like `defmacro', but macro expansion occurs only if the call to
2611 FUNC is compiled (i.e., not interpreted).  Compiler macros should be used
2612 for optimizing the way calls to FUNC are compiled; the form returned by
2613 BODY should do the same thing as a call to the normal function called
2614 FUNC, though possibly more efficiently.  Note that, like regular macros,
2615 compiler macros are expanded repeatedly until no further expansions are
2616 possible.  Unlike regular macros, BODY can decide to \"punt\" and leave the
2617 original function call alone by declaring an initial `&whole foo' parameter
2618 and then returning foo."
2619   (let ((p (if (listp args) args (list '&rest args))) (res nil))
2620     (while (consp p) (cl-push (cl-pop p) res))
2621     (setq args (nreverse res)) (setcdr res (and p (list '&rest p))))
2622   (list 'eval-when '(compile load eval)
2623         (cl-transform-function-property
2624          func 'cl-compiler-macro
2625          (cons (if (memq '&whole args) (delq '&whole args)
2626                  (cons '--cl-whole-arg-- args)) body))
2627         (list 'or (list 'get (list 'quote func) '(quote byte-compile))
2628               (list 'put (list 'quote func) '(quote byte-compile)
2629                     '(quote cl-byte-compile-compiler-macro)))))
2630
2631 ;;;###autoload
2632 (defun compiler-macroexpand (form)
2633   (while
2634       (let ((func (car-safe form)) (handler nil))
2635         (while (and (symbolp func)
2636                     (not (setq handler (get func 'cl-compiler-macro)))
2637                     (fboundp func)
2638                     (or (not (eq (car-safe (symbol-function func)) 'autoload))
2639                         (load (nth 1 (symbol-function func)))))
2640           (setq func (symbol-function func)))
2641         (and handler
2642              (not (eq form (setq form (apply handler form (cdr form))))))))
2643   form)
2644
2645 (defun cl-byte-compile-compiler-macro (form)
2646   (if (eq form (setq form (compiler-macroexpand form)))
2647       (byte-compile-normal-call form)
2648     (byte-compile-form form)))
2649
2650 (defmacro defsubst* (name args &rest body)
2651   "(defsubst* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
2652 Like `defun', except the function is automatically declared `inline',
2653 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2654 surrounded by (block NAME ...)."
2655   (let* ((argns (cl-arglist-args args)) (p argns)
2656          (pbody (cons 'progn body))
2657          (unsafe (not (cl-safe-expr-p pbody))))
2658     (while (and p (eq (cl-expr-contains args (car p)) 1)) (cl-pop p))
2659     (list 'progn
2660           (if p nil   ; give up if defaults refer to earlier args
2661             (list 'define-compiler-macro name
2662                   (list* '&whole 'cl-whole '&cl-quote args)
2663                   (list* 'cl-defsubst-expand (list 'quote argns)
2664                          (list 'quote (list* 'block name body))
2665                          (not (or unsafe (cl-expr-access-order pbody argns)))
2666                          (and (memq '&key args) 'cl-whole) unsafe argns)))
2667           (list* 'defun* name args body))))
2668
2669 (defun cl-defsubst-expand (argns body simple whole unsafe &rest argvs)
2670   (if (and whole (not (cl-safe-expr-p (cons 'progn argvs)))) whole
2671     (if (cl-simple-exprs-p argvs) (setq simple t))
2672     (let ((lets (delq nil
2673                       (mapcar* (function
2674                                 (lambda (argn argv)
2675                                   (if (or simple (cl-const-expr-p argv))
2676                                       (progn (setq body (subst argv argn body))
2677                                              (and unsafe (list argn argv)))
2678                                     (list argn argv))))
2679                                argns argvs))))
2680       (if lets (list 'let lets body) body))))
2681
2682
2683 ;;; Compile-time optimizations for some functions defined in this package.
2684 ;;; Note that cl.el arranges to force cl-macs to be loaded at compile-time,
2685 ;;; mainly to make sure these macros will be present.
2686
2687 (put 'eql 'byte-compile nil)
2688 (define-compiler-macro eql (&whole form a b)
2689   (cond ((eq (cl-const-expr-p a) t)
2690          (let ((val (cl-const-expr-val a)))
2691            (if (and (numberp val) (not (integerp val)))
2692                (list 'equal a b)
2693              (list 'eq a b))))
2694         ((eq (cl-const-expr-p b) t)
2695          (let ((val (cl-const-expr-val b)))
2696            (if (and (numberp val) (not (integerp val)))
2697                (list 'equal a b)
2698              (list 'eq a b))))
2699         ((cl-simple-expr-p a 5)
2700          (list 'if (list 'numberp a)
2701                (list 'equal a b)
2702                (list 'eq a b)))
2703         ((and (cl-safe-expr-p a)
2704               (cl-simple-expr-p b 5))
2705          (list 'if (list 'numberp b)
2706                (list 'equal a b)
2707                (list 'eq a b)))
2708         (t form)))
2709
2710 (define-compiler-macro member* (&whole form a list &rest keys)
2711   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
2712                    (cl-const-expr-val (nth 1 keys)))))
2713     (cond ((eq test 'eq) (list 'memq a list))
2714           ((eq test 'equal) (list 'member a list))
2715           ((or (null keys) (eq test 'eql))
2716            (if (eq (cl-const-expr-p a) t)
2717                (list (if (floatp-safe (cl-const-expr-val a)) 'member 'memq)
2718                      a list)
2719              (if (eq (cl-const-expr-p list) t)
2720                  (let ((p (cl-const-expr-val list)) (mb nil) (mq nil))
2721                    (if (not (cdr p))
2722                        (and p (list 'eql a (list 'quote (car p))))
2723                      (while p
2724                        (if (floatp-safe (car p)) (setq mb t)
2725                          (or (integerp (car p)) (symbolp (car p)) (setq mq t)))
2726                        (setq p (cdr p)))
2727                      (if (not mb) (list 'memq a list)
2728                        (if (not mq) (list 'member a list) form))))
2729                form)))
2730           (t form))))
2731
2732 (define-compiler-macro assoc* (&whole form a list &rest keys)
2733   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
2734                    (cl-const-expr-val (nth 1 keys)))))
2735     (cond ((eq test 'eq) (list 'assq a list))
2736           ((eq test 'equal) (list 'assoc a list))
2737           ((and (eq (cl-const-expr-p a) t) (or (null keys) (eq test 'eql)))
2738            (if (floatp-safe (cl-const-expr-val a))
2739                (list 'assoc a list) (list 'assq a list)))
2740           (t form))))
2741
2742 (define-compiler-macro adjoin (&whole form a list &rest keys)
2743   (if (and (cl-simple-expr-p a) (cl-simple-expr-p list)
2744            (not (memq ':key keys)))
2745       (list 'if (list* 'member* a list keys) list (list 'cons a list))
2746     form))
2747
2748 (define-compiler-macro list* (arg &rest others)
2749   (let* ((args (reverse (cons arg others)))
2750          (form (car args)))
2751     (while (setq args (cdr args))
2752       (setq form (list 'cons (car args) form)))
2753     form))
2754
2755 (define-compiler-macro get* (sym prop &optional def)
2756   (if def
2757       (list 'getf (list 'symbol-plist sym) prop def)
2758     (list 'get sym prop)))
2759
2760 (define-compiler-macro typep (&whole form val type)
2761   (if (cl-const-expr-p type)
2762       (let ((res (cl-make-type-test val (cl-const-expr-val type))))
2763         (if (or (memq (cl-expr-contains res val) '(nil 1))
2764                 (cl-simple-expr-p val)) res
2765           (let ((temp (gensym)))
2766             (list 'let (list (list temp val)) (subst temp val res)))))
2767     form))
2768
2769
2770 (mapcar (function
2771          (lambda (y)
2772            (put (car y) 'side-effect-free t)
2773            (put (car y) 'byte-compile 'cl-byte-compile-compiler-macro)
2774            (put (car y) 'cl-compiler-macro
2775                 (list 'lambda '(w x)
2776                       (if (symbolp (cadr y))
2777                           (list 'list (list 'quote (cadr y))
2778                                 (list 'list (list 'quote (caddr y)) 'x))
2779                         (cons 'list (cdr y)))))))
2780         '((first 'car x) (second 'cadr x) (third 'caddr x) (fourth 'cadddr x)
2781           (fifth 'nth 4 x) (sixth 'nth 5 x) (seventh 'nth 6 x)
2782           (eighth 'nth 7 x) (ninth 'nth 8 x) (tenth 'nth 9 x)
2783           (rest 'cdr x) (endp 'null x) (plusp '> x 0) (minusp '< x 0)
2784           (caar car car) (cadr car cdr) (cdar cdr car) (cddr cdr cdr)
2785           (caaar car caar) (caadr car cadr) (cadar car cdar)
2786           (caddr car cddr) (cdaar cdr caar) (cdadr cdr cadr)
2787           (cddar cdr cdar) (cdddr cdr cddr) (caaaar car caaar)
2788           (caaadr car caadr) (caadar car cadar) (caaddr car caddr)
2789           (cadaar car cdaar) (cadadr car cdadr) (caddar car cddar)
2790           (cadddr car cdddr) (cdaaar cdr caaar) (cdaadr cdr caadr)
2791           (cdadar cdr cadar) (cdaddr cdr caddr) (cddaar cdr cdaar)
2792           (cddadr cdr cdadr) (cdddar cdr cddar) (cddddr cdr cdddr) ))
2793
2794 ;;; Things that are inline.
2795 (proclaim '(inline floatp-safe acons map concatenate notany notevery
2796 ;; XEmacs change
2797                    cl-set-elt revappend nreconc))
2798
2799 ;;; Things that are side-effect-free.
2800 (mapcar (function (lambda (x) (put x 'side-effect-free t)))
2801         '(oddp evenp abs expt signum last butlast ldiff pairlis gcd lcm
2802           isqrt floor* ceiling* truncate* round* mod* rem* subseq
2803           list-length get* getf gethash hash-table-count))
2804
2805 ;;; Things that are side-effect-and-error-free.
2806 (mapcar (function (lambda (x) (put x 'side-effect-free 'error-free)))
2807         '(eql floatp-safe list* subst acons equalp random-state-p
2808           copy-tree sublis hash-table-p))
2809
2810
2811 (run-hooks 'cl-macs-load-hook)
2812
2813 ;;; cl-macs.el ends here