XEmacs 21.2-b2
[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 glyph-image (glyph &optional domain) (i)
1735   (list 'set-glyph-image glyph i domain))
1736 (defsetf itimer-function set-itimer-function)
1737 (defsetf itimer-function-arguments set-itimer-function-arguments)
1738 (defsetf itimer-is-idle set-itimer-is-idle)
1739 (defsetf itimer-recorded-run-time set-itimer-recorded-run-time)
1740 (defsetf itimer-restart set-itimer-restart)
1741 (defsetf itimer-uses-arguments set-itimer-uses-arguments)
1742 (defsetf itimer-value set-itimer-value)
1743 (defsetf keymap-parents set-keymap-parents)
1744 (defsetf marker-insertion-type set-marker-insertion-type)
1745 (defsetf mouse-pixel-position (&optional d) (v)
1746   `(progn
1747      set-mouse-pixel-position ,d ,(car v) ,(car (cdr v)) ,(cdr (cdr v))
1748      ,v))
1749 (defsetf trunc-stack-length set-trunc-stack-length)
1750 (defsetf trunc-stack-stack set-trunc-stack-stack)
1751 (defsetf undoable-stack-max set-undoable-stack-max)
1752 (defsetf weak-list-list set-weak-list-list)
1753
1754
1755 (defsetf getenv setenv t)
1756 (defsetf get-register set-register)
1757 (defsetf global-key-binding global-set-key)
1758 (defsetf keymap-parent set-keymap-parent)
1759 (defsetf keymap-name set-keymap-name)
1760 (defsetf keymap-prompt set-keymap-prompt)
1761 (defsetf keymap-default-binding set-keymap-default-binding)
1762 (defsetf local-key-binding local-set-key)
1763 (defsetf mark set-mark t)
1764 (defsetf mark-marker set-mark t)
1765 (defsetf marker-position set-marker t)
1766 (defsetf match-data store-match-data t)
1767 (defsetf mouse-position (scr) (store)
1768   (list 'set-mouse-position scr (list 'car store) (list 'cadr store)
1769         (list 'cddr store)))
1770 (defsetf overlay-get overlay-put)
1771 (defsetf overlay-start (ov) (store)
1772   (list 'progn (list 'move-overlay ov store (list 'overlay-end ov)) store))
1773 (defsetf overlay-end (ov) (store)
1774   (list 'progn (list 'move-overlay ov (list 'overlay-start ov) store) store))
1775 (defsetf point goto-char)
1776 (defsetf point-marker goto-char t)
1777 (defsetf point-max () (store)
1778   (list 'progn (list 'narrow-to-region '(point-min) store) store))
1779 (defsetf point-min () (store)
1780   (list 'progn (list 'narrow-to-region store '(point-max)) store))
1781 (defsetf process-buffer set-process-buffer)
1782 (defsetf process-filter set-process-filter)
1783 (defsetf process-sentinel set-process-sentinel)
1784 (defsetf read-mouse-position (scr) (store)
1785   (list 'set-mouse-position scr (list 'car store) (list 'cdr store)))
1786 (defsetf selected-window select-window)
1787 (defsetf selected-frame select-frame)
1788 (defsetf standard-case-table set-standard-case-table)
1789 (defsetf syntax-table set-syntax-table)
1790 (defsetf visited-file-modtime set-visited-file-modtime t)
1791 (defsetf window-buffer set-window-buffer t)
1792 (defsetf window-display-table set-window-display-table t)
1793 (defsetf window-dedicated-p set-window-dedicated-p t)
1794 (defsetf window-height () (store)
1795   (list 'progn (list 'enlarge-window (list '- store '(window-height))) store))
1796 (defsetf window-hscroll set-window-hscroll)
1797 (defsetf window-point set-window-point)
1798 (defsetf window-start set-window-start)
1799 (defsetf window-width () (store)
1800   (list 'progn (list 'enlarge-window (list '- store '(window-width)) t) store))
1801 (defsetf x-get-cutbuffer x-store-cutbuffer t)
1802 (defsetf x-get-cut-buffer x-store-cut-buffer t)   ; groan.
1803 (defsetf x-get-secondary-selection x-own-secondary-selection t)
1804 (defsetf x-get-selection x-own-selection t)
1805
1806 ;;; More complex setf-methods.
1807 ;;; These should take &environment arguments, but since full arglists aren't
1808 ;;; available while compiling cl-macs, we fake it by referring to the global
1809 ;;; variable cl-macro-environment directly.
1810
1811 (define-setf-method apply (func arg1 &rest rest)
1812   (or (and (memq (car-safe func) '(quote function function*))
1813            (symbolp (car-safe (cdr-safe func))))
1814       (error "First arg to apply in setf is not (function SYM): %s" func))
1815   (let* ((form (cons (nth 1 func) (cons arg1 rest)))
1816          (method (get-setf-method form cl-macro-environment)))
1817     (list (car method) (nth 1 method) (nth 2 method)
1818           (cl-setf-make-apply (nth 3 method) (cadr func) (car method))
1819           (cl-setf-make-apply (nth 4 method) (cadr func) (car method)))))
1820
1821 (defun cl-setf-make-apply (form func temps)
1822   (if (eq (car form) 'progn)
1823       (list* 'progn (cl-setf-make-apply (cadr form) func temps) (cddr form))
1824     (or (equal (last form) (last temps))
1825         (error "%s is not suitable for use with setf-of-apply" func))
1826     (list* 'apply (list 'quote (car form)) (cdr form))))
1827
1828 (define-setf-method nthcdr (n place)
1829   (let ((method (get-setf-method place cl-macro-environment))
1830         (n-temp (gensym "--nthcdr-n--"))
1831         (store-temp (gensym "--nthcdr-store--")))
1832     (list (cons n-temp (car method))
1833           (cons n (nth 1 method))
1834           (list store-temp)
1835           (list 'let (list (list (car (nth 2 method))
1836                                  (list 'cl-set-nthcdr n-temp (nth 4 method)
1837                                        store-temp)))
1838                 (nth 3 method) store-temp)
1839           (list 'nthcdr n-temp (nth 4 method)))))
1840
1841 (define-setf-method getf (place tag &optional def)
1842   (let ((method (get-setf-method place cl-macro-environment))
1843         (tag-temp (gensym "--getf-tag--"))
1844         (def-temp (gensym "--getf-def--"))
1845         (store-temp (gensym "--getf-store--")))
1846     (list (append (car method) (list tag-temp def-temp))
1847           (append (nth 1 method) (list tag def))
1848           (list store-temp)
1849           (list 'let (list (list (car (nth 2 method))
1850                                  (list 'cl-set-getf (nth 4 method)
1851                                        tag-temp store-temp)))
1852                 (nth 3 method) store-temp)
1853           (list 'getf (nth 4 method) tag-temp def-temp))))
1854
1855 (define-setf-method substring (place from &optional to)
1856   (let ((method (get-setf-method place cl-macro-environment))
1857         (from-temp (gensym "--substring-from--"))
1858         (to-temp (gensym "--substring-to--"))
1859         (store-temp (gensym "--substring-store--")))
1860     (list (append (car method) (list from-temp to-temp))
1861           (append (nth 1 method) (list from to))
1862           (list store-temp)
1863           (list 'let (list (list (car (nth 2 method))
1864                                  (list 'cl-set-substring (nth 4 method)
1865                                        from-temp to-temp store-temp)))
1866                 (nth 3 method) store-temp)
1867           (list 'substring (nth 4 method) from-temp to-temp))))
1868
1869 (define-setf-method values (&rest args)
1870   (let ((methods (mapcar #'(lambda (x)
1871                              (get-setf-method x cl-macro-environment))
1872                          args))
1873         (store-temp (gensym "--values-store--")))
1874     (list (apply 'append (mapcar 'first methods))
1875           (apply 'append (mapcar 'second methods))
1876           (list store-temp)
1877           (cons 'list
1878                 (mapcar #'(lambda (m)
1879                             (cl-setf-do-store (cons (car (third m)) (fourth m))
1880                                               (list 'pop store-temp)))
1881                         methods))
1882           (cons 'list (mapcar 'fifth methods)))))
1883
1884 ;;; Getting and optimizing setf-methods.
1885 ;;;###autoload
1886 (defun get-setf-method (place &optional env)
1887   "Return a list of five values describing the setf-method for PLACE.
1888 PLACE may be any Lisp form which can appear as the PLACE argument to
1889 a macro like `setf' or `incf'."
1890   (if (symbolp place)
1891       (let ((temp (gensym "--setf--")))
1892         (list nil nil (list temp) (list 'setq place temp) place))
1893     (or (and (symbolp (car place))
1894              (let* ((func (car place))
1895                     (name (symbol-name func))
1896                     (method (get func 'setf-method))
1897                     (case-fold-search nil))
1898                (or (and method
1899                         (let ((cl-macro-environment env))
1900                           (setq method (apply method (cdr place))))
1901                         (if (and (consp method) (= (length method) 5))
1902                             method
1903                           (error "Setf-method for %s returns malformed method"
1904                                  func)))
1905                    (and (save-match-data
1906                           (string-match "\\`c[ad][ad][ad]?[ad]?r\\'" name))
1907                         (get-setf-method (compiler-macroexpand place)))
1908                    (and (eq func 'edebug-after)
1909                         (get-setf-method (nth (1- (length place)) place)
1910                                          env)))))
1911         (if (eq place (setq place (macroexpand place env)))
1912             (if (and (symbolp (car place)) (fboundp (car place))
1913                      (symbolp (symbol-function (car place))))
1914                 (get-setf-method (cons (symbol-function (car place))
1915                                        (cdr place)) env)
1916               (error "No setf-method known for %s" (car place)))
1917           (get-setf-method place env)))))
1918
1919 (defun cl-setf-do-modify (place opt-expr)
1920   (let* ((method (get-setf-method place cl-macro-environment))
1921          (temps (car method)) (values (nth 1 method))
1922          (lets nil) (subs nil)
1923          (optimize (and (not (eq opt-expr 'no-opt))
1924                         (or (and (not (eq opt-expr 'unsafe))
1925                                  (cl-safe-expr-p opt-expr))
1926                             (cl-setf-simple-store-p (car (nth 2 method))
1927                                                     (nth 3 method)))))
1928          (simple (and optimize (consp place) (cl-simple-exprs-p (cdr place)))))
1929     (while values
1930       (if (or simple (cl-const-expr-p (car values)))
1931           (cl-push (cons (cl-pop temps) (cl-pop values)) subs)
1932         (cl-push (list (cl-pop temps) (cl-pop values)) lets)))
1933     (list (nreverse lets)
1934           (cons (car (nth 2 method)) (sublis subs (nth 3 method)))
1935           (sublis subs (nth 4 method)))))
1936
1937 (defun cl-setf-do-store (spec val)
1938   (let ((sym (car spec))
1939         (form (cdr spec)))
1940     (if (or (cl-const-expr-p val)
1941             (and (cl-simple-expr-p val) (eq (cl-expr-contains form sym) 1))
1942             (cl-setf-simple-store-p sym form))
1943         (subst val sym form)
1944       (list 'let (list (list sym val)) form))))
1945
1946 (defun cl-setf-simple-store-p (sym form)
1947   (and (consp form) (eq (cl-expr-contains form sym) 1)
1948        (eq (nth (1- (length form)) form) sym)
1949        (symbolp (car form)) (fboundp (car form))
1950        (not (eq (car-safe (symbol-function (car form))) 'macro))))
1951
1952 ;;; The standard modify macros.
1953 ;;;###autoload
1954 (defmacro setf (&rest args)
1955   "(setf PLACE VAL PLACE VAL ...): set each PLACE to the value of its VAL.
1956 This is a generalized version of `setq'; the PLACEs may be symbolic
1957 references such as (car x) or (aref x i), as well as plain symbols.
1958 For example, (setf (cadar x) y) is equivalent to (setcar (cdar x) y).
1959 The return value is the last VAL in the list."
1960   (if (cdr (cdr args))
1961       (let ((sets nil))
1962         (while args (cl-push (list 'setf (cl-pop args) (cl-pop args)) sets))
1963         (cons 'progn (nreverse sets)))
1964     (if (symbolp (car args))
1965         (and args (cons 'setq args))
1966       (let* ((method (cl-setf-do-modify (car args) (nth 1 args)))
1967              (store (cl-setf-do-store (nth 1 method) (nth 1 args))))
1968         (if (car method) (list 'let* (car method) store) store)))))
1969
1970 ;;;###autoload
1971 (defmacro psetf (&rest args)
1972   "(psetf PLACE VAL PLACE VAL ...): set PLACEs to the values VALs in parallel.
1973 This is like `setf', except that all VAL forms are evaluated (in order)
1974 before assigning any PLACEs to the corresponding values."
1975   (let ((p args) (simple t) (vars nil))
1976     (while p
1977       (if (or (not (symbolp (car p))) (cl-expr-depends-p (nth 1 p) vars))
1978           (setq simple nil))
1979       (if (memq (car p) vars)
1980           (error "Destination duplicated in psetf: %s" (car p)))
1981       (cl-push (cl-pop p) vars)
1982       (or p (error "Odd number of arguments to psetf"))
1983       (cl-pop p))
1984     (if simple
1985         (list 'progn (cons 'setf args) nil)
1986       (setq args (reverse args))
1987       (let ((expr (list 'setf (cadr args) (car args))))
1988         (while (setq args (cddr args))
1989           (setq expr (list 'setf (cadr args) (list 'prog1 (car args) expr))))
1990         (list 'progn expr nil)))))
1991
1992 ;;;###autoload
1993 (defun cl-do-pop (place)
1994   (if (cl-simple-expr-p place)
1995       (list 'prog1 (list 'car place) (list 'setf place (list 'cdr place)))
1996     (let* ((method (cl-setf-do-modify place t))
1997            (temp (gensym "--pop--")))
1998       (list 'let*
1999             (append (car method)
2000                     (list (list temp (nth 2 method))))
2001             (list 'prog1
2002                   (list 'car temp)
2003                   (cl-setf-do-store (nth 1 method) (list 'cdr temp)))))))
2004
2005 ;;;###autoload
2006 (defmacro remf (place tag)
2007   "(remf PLACE TAG): remove TAG from property list PLACE.
2008 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2009 The form returns true if TAG was found and removed, nil otherwise."
2010   (let* ((method (cl-setf-do-modify place t))
2011          (tag-temp (and (not (cl-const-expr-p tag)) (gensym "--remf-tag--")))
2012          (val-temp (and (not (cl-simple-expr-p place))
2013                         (gensym "--remf-place--")))
2014          (ttag (or tag-temp tag))
2015          (tval (or val-temp (nth 2 method))))
2016     (list 'let*
2017           (append (car method)
2018                   (and val-temp (list (list val-temp (nth 2 method))))
2019                   (and tag-temp (list (list tag-temp tag))))
2020           (list 'if (list 'eq ttag (list 'car tval))
2021                 (list 'progn
2022                       (cl-setf-do-store (nth 1 method) (list 'cddr tval))
2023                       t)
2024                 (list 'cl-do-remf tval ttag)))))
2025
2026 ;;;###autoload
2027 (defmacro shiftf (place &rest args)
2028   "(shiftf PLACE PLACE... VAL): shift left among PLACEs.
2029 Example: (shiftf A B C) sets A to B, B to C, and returns the old A.
2030 Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
2031   (if (not (memq nil (mapcar 'symbolp (butlast (cons place args)))))
2032       (list* 'prog1 place
2033              (let ((sets nil))
2034                (while args
2035                  (cl-push (list 'setq place (car args)) sets)
2036                  (setq place (cl-pop args)))
2037                (nreverse sets)))
2038     (let* ((places (reverse (cons place args)))
2039            (form (cl-pop places)))
2040       (while places
2041         (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
2042           (setq form (list 'let* (car method)
2043                            (list 'prog1 (nth 2 method)
2044                                  (cl-setf-do-store (nth 1 method) form))))))
2045       form)))
2046
2047 ;;;###autoload
2048 (defmacro rotatef (&rest args)
2049   "(rotatef PLACE...): rotate left among PLACEs.
2050 Example: (rotatef A B C) sets A to B, B to C, and C to A.  It returns nil.
2051 Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
2052   (if (not (memq nil (mapcar 'symbolp args)))
2053       (and (cdr args)
2054            (let ((sets nil)
2055                  (first (car args)))
2056              (while (cdr args)
2057                (setq sets (nconc sets (list (cl-pop args) (car args)))))
2058              (nconc (list 'psetf) sets (list (car args) first))))
2059     (let* ((places (reverse args))
2060            (temp (gensym "--rotatef--"))
2061            (form temp))
2062       (while (cdr places)
2063         (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
2064           (setq form (list 'let* (car method)
2065                            (list 'prog1 (nth 2 method)
2066                                  (cl-setf-do-store (nth 1 method) form))))))
2067       (let ((method (cl-setf-do-modify (car places) 'unsafe)))
2068         (list 'let* (append (car method) (list (list temp (nth 2 method))))
2069               (cl-setf-do-store (nth 1 method) form) nil)))))
2070
2071 ;;;###autoload
2072 (defmacro letf (bindings &rest body)
2073   "(letf ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
2074 This is the analogue of `let', but with generalized variables (in the
2075 sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
2076 VALUE, then the BODY forms are executed.  On exit, either normally or
2077 because of a `throw' or error, the PLACEs are set back to their original
2078 values.  Note that this macro is *not* available in Common Lisp.
2079 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2080 the PLACE is not modified before executing BODY."
2081   (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2082       (list* 'let bindings body)
2083     (let ((lets nil) (sets nil)
2084           (unsets nil) (rev (reverse bindings)))
2085       (while rev
2086         (let* ((place (if (symbolp (caar rev))
2087                           (list 'symbol-value (list 'quote (caar rev)))
2088                         (caar rev)))
2089                (value (cadar rev))
2090                (method (cl-setf-do-modify place 'no-opt))
2091                (save (gensym "--letf-save--"))
2092                (bound (and (memq (car place) '(symbol-value symbol-function))
2093                            (gensym "--letf-bound--")))
2094                (temp (and (not (cl-const-expr-p value)) (cdr bindings)
2095                           (gensym "--letf-val--"))))
2096           (setq lets (nconc (car method)
2097                             (if bound
2098                                 (list (list bound
2099                                             (list (if (eq (car place)
2100                                                           'symbol-value)
2101                                                       'boundp 'fboundp)
2102                                                   (nth 1 (nth 2 method))))
2103                                       (list save (list 'and bound
2104                                                        (nth 2 method))))
2105                               (list (list save (nth 2 method))))
2106                             (and temp (list (list temp value)))
2107                             lets)
2108                 body (list
2109                       (list 'unwind-protect
2110                             (cons 'progn
2111                                   (if (cdr (car rev))
2112                                       (cons (cl-setf-do-store (nth 1 method)
2113                                                               (or temp value))
2114                                             body)
2115                                     body))
2116                             (if bound
2117                                 (list 'if bound
2118                                       (cl-setf-do-store (nth 1 method) save)
2119                                       (list (if (eq (car place) 'symbol-value)
2120                                                 'makunbound 'fmakunbound)
2121                                             (nth 1 (nth 2 method))))
2122                               (cl-setf-do-store (nth 1 method) save))))
2123                 rev (cdr rev))))
2124       (list* 'let* lets body))))
2125
2126 ;;;###autoload
2127 (defmacro letf* (bindings &rest body)
2128   "(letf* ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
2129 This is the analogue of `let*', but with generalized variables (in the
2130 sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
2131 VALUE, then the BODY forms are executed.  On exit, either normally or
2132 because of a `throw' or error, the PLACEs are set back to their original
2133 values.  Note that this macro is *not* available in Common Lisp.
2134 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2135 the PLACE is not modified before executing BODY."
2136   (if (null bindings)
2137       (cons 'progn body)
2138     (setq bindings (reverse bindings))
2139     (while bindings
2140       (setq body (list (list* 'letf (list (cl-pop bindings)) body))))
2141     (car body)))
2142
2143 ;;;###autoload
2144 (defmacro callf (func place &rest args)
2145   "(callf FUNC PLACE ARGS...): set PLACE to (FUNC PLACE ARGS...).
2146 FUNC should be an unquoted function name.  PLACE may be a symbol,
2147 or any generalized variable allowed by `setf'."
2148   (let* ((method (cl-setf-do-modify place (cons 'list args)))
2149          (rargs (cons (nth 2 method) args)))
2150     (list 'let* (car method)
2151           (cl-setf-do-store (nth 1 method)
2152                             (if (symbolp func) (cons func rargs)
2153                               (list* 'funcall (list 'function func)
2154                                      rargs))))))
2155
2156 ;;;###autoload
2157 (defmacro callf2 (func arg1 place &rest args)
2158   "(callf2 FUNC ARG1 PLACE ARGS...): set PLACE to (FUNC ARG1 PLACE ARGS...).
2159 Like `callf', but PLACE is the second argument of FUNC, not the first."
2160   (if (and (cl-safe-expr-p arg1) (cl-simple-expr-p place) (symbolp func))
2161       (list 'setf place (list* func arg1 place args))
2162     (let* ((method (cl-setf-do-modify place (cons 'list args)))
2163            (temp (and (not (cl-const-expr-p arg1)) (gensym "--arg1--")))
2164            (rargs (list* (or temp arg1) (nth 2 method) args)))
2165       (list 'let* (append (and temp (list (list temp arg1))) (car method))
2166             (cl-setf-do-store (nth 1 method)
2167                               (if (symbolp func) (cons func rargs)
2168                                 (list* 'funcall (list 'function func)
2169                                        rargs)))))))
2170
2171 ;;;###autoload
2172 (defmacro define-modify-macro (name arglist func &optional doc)
2173   "(define-modify-macro NAME ARGLIST FUNC): define a `setf'-like modify macro.
2174 If NAME is called, it combines its PLACE argument with the other arguments
2175 from ARGLIST using FUNC: (define-modify-macro incf (&optional (n 1)) +)"
2176   (if (memq '&key arglist) (error "&key not allowed in define-modify-macro"))
2177   (let ((place (gensym "--place--")))
2178     (list 'defmacro* name (cons place arglist) doc
2179           (list* (if (memq '&rest arglist) 'list* 'list)
2180                  '(quote callf) (list 'quote func) place
2181                  (cl-arglist-args arglist)))))
2182
2183
2184 ;;; Structures.
2185
2186 ;;;###autoload
2187 (defmacro defstruct (struct &rest descs)
2188   "(defstruct (NAME OPTIONS...) (SLOT SLOT-OPTS...)...): define a struct type.
2189 This macro defines a new Lisp data type called NAME, which contains data
2190 stored in SLOTs.  This defines a `make-NAME' constructor, a `copy-NAME'
2191 copier, a `NAME-p' predicate, and setf-able `NAME-SLOT' accessors."
2192   (let* ((name (if (consp struct) (car struct) struct))
2193          (opts (cdr-safe struct))
2194          (slots nil)
2195          (defaults nil)
2196          (conc-name (concat (symbol-name name) "-"))
2197          (constructor (intern (format "make-%s" name)))
2198          (constrs nil)
2199          (copier (intern (format "copy-%s" name)))
2200          (predicate (intern (format "%s-p" name)))
2201          (print-func nil) (print-auto nil)
2202          (safety (if (cl-compiling-file) cl-optimize-safety 3))
2203          (include nil)
2204          (tag (intern (format "cl-struct-%s" name)))
2205          (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2206          (include-descs nil)
2207          ;; XEmacs change
2208          (include-tag-symbol nil)
2209          (side-eff nil)
2210          (type nil)
2211          (named nil)
2212          (forms nil)
2213          pred-form pred-check)
2214     (if (stringp (car descs))
2215         (cl-push (list 'put (list 'quote name) '(quote structure-documentation)
2216                        (cl-pop descs)) forms))
2217     (setq descs (cons '(cl-tag-slot)
2218                       (mapcar (function (lambda (x) (if (consp x) x (list x))))
2219                               descs)))
2220     (while opts
2221       (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2222             (args (cdr-safe (cl-pop opts))))
2223         (cond ((eq opt ':conc-name)
2224                (if args
2225                    (setq conc-name (if (car args)
2226                                        (symbol-name (car args)) ""))))
2227               ((eq opt ':constructor)
2228                (if (cdr args)
2229                    (cl-push args constrs)
2230                  (if args (setq constructor (car args)))))
2231               ((eq opt ':copier)
2232                (if args (setq copier (car args))))
2233               ((eq opt ':predicate)
2234                (if args (setq predicate (car args))))
2235               ((eq opt ':include)
2236                (setq include (car args)
2237                      include-descs (mapcar (function
2238                                             (lambda (x)
2239                                               (if (consp x) x (list x))))
2240                                            (cdr args))
2241                      ;; XEmacs change
2242                      include-tag-symbol (intern (format "cl-struct-%s-tags"
2243                                                         include))))
2244               ((eq opt ':print-function)
2245                (setq print-func (car args)))
2246               ((eq opt ':type)
2247                (setq type (car args)))
2248               ((eq opt ':named)
2249                (setq named t))
2250               ((eq opt ':initial-offset)
2251                (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2252                                   descs)))
2253               (t
2254                (error "Slot option %s unrecognized" opt)))))
2255     (if print-func
2256         (setq print-func (list 'progn
2257                                (list 'funcall (list 'function print-func)
2258                                      'cl-x 'cl-s 'cl-n) t))
2259       (or type (and include (not (get include 'cl-struct-print)))
2260           (setq print-auto t
2261                 print-func (and (or (not (or include type)) (null print-func))
2262                                 (list 'progn
2263                                       (list 'princ (format "#S(%s" name)
2264                                             'cl-s))))))
2265     (if include
2266         (let ((inc-type (get include 'cl-struct-type))
2267               (old-descs (get include 'cl-struct-slots)))
2268           (or inc-type (error "%s is not a struct name" include))
2269           (and type (not (eq (car inc-type) type))
2270                (error ":type disagrees with :include for %s" name))
2271           (while include-descs
2272             (setcar (memq (or (assq (caar include-descs) old-descs)
2273                               (error "No slot %s in included struct %s"
2274                                      (caar include-descs) include))
2275                           old-descs)
2276                     (cl-pop include-descs)))
2277           (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2278                 type (car inc-type)
2279                 named (assq 'cl-tag-slot descs))
2280           (if (cadr inc-type) (setq tag name named t))
2281           (let ((incl include))
2282             (while incl
2283               (cl-push (list 'pushnew (list 'quote tag)
2284                              (intern (format "cl-struct-%s-tags" incl)))
2285                        forms)
2286               (setq incl (get incl 'cl-struct-include)))))
2287       (if type
2288           (progn
2289             (or (memq type '(vector list))
2290                 (error "Illegal :type specifier: %s" type))
2291             (if named (setq tag name)))
2292         (setq type 'vector named 'true)))
2293     (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2294     (cl-push (list 'defvar tag-symbol) forms)
2295     (setq pred-form (and named
2296                          (let ((pos (- (length descs)
2297                                        (length (memq (assq 'cl-tag-slot descs)
2298                                                      descs)))))
2299                            (if (eq type 'vector)
2300                                (list 'and '(vectorp cl-x)
2301                                      (list '>= '(length cl-x) (length descs))
2302                                      (list 'memq (list 'aref 'cl-x pos)
2303                                            tag-symbol))
2304                              (if (= pos 0)
2305                                  (list 'memq '(car-safe cl-x) tag-symbol)
2306                                (list 'and '(consp cl-x)
2307                                      (list 'memq (list 'nth pos 'cl-x)
2308                                            tag-symbol))))))
2309           pred-check (and pred-form (> safety 0)
2310                           (if (and (eq (caadr pred-form) 'vectorp)
2311                                    (= safety 1))
2312                               (cons 'and (cdddr pred-form)) pred-form)))
2313     (let ((pos 0) (descp descs))
2314       (while descp
2315         (let* ((desc (cl-pop descp))
2316                (slot (car desc)))
2317           (if (memq slot '(cl-tag-slot cl-skip-slot))
2318               (progn
2319                 (cl-push nil slots)
2320                 (cl-push (and (eq slot 'cl-tag-slot) (list 'quote tag))
2321                          defaults))
2322             (if (assq slot descp)
2323                 (error "Duplicate slots named %s in %s" slot name))
2324             (let ((accessor (intern (format "%s%s" conc-name slot))))
2325               (cl-push slot slots)
2326               (cl-push (nth 1 desc) defaults)
2327               (cl-push (list*
2328                         'defsubst* accessor '(cl-x)
2329                         (append
2330                          (and pred-check
2331                               (list (list 'or pred-check
2332                                           (list 'error
2333                                                 (format "%s accessing a non-%s"
2334                                                         accessor name)
2335                                                 'cl-x))))
2336                          (list (if (eq type 'vector) (list 'aref 'cl-x pos)
2337                                  (if (= pos 0) '(car cl-x)
2338                                    (list 'nth pos 'cl-x)))))) forms)
2339               (cl-push (cons accessor t) side-eff)
2340               (cl-push (list 'define-setf-method accessor '(cl-x)
2341                              (if (cadr (memq ':read-only (cddr desc)))
2342                                  (list 'error (format "%s is a read-only slot"
2343                                                       accessor))
2344                                (list 'cl-struct-setf-expander 'cl-x
2345                                      (list 'quote name) (list 'quote accessor)
2346                                      (and pred-check (list 'quote pred-check))
2347                                      pos)))
2348                        forms)
2349               (if print-auto
2350                   (nconc print-func
2351                          (list (list 'princ (format " %s" slot) 'cl-s)
2352                                (list 'prin1 (list accessor 'cl-x) 'cl-s)))))))
2353         (setq pos (1+ pos))))
2354     (setq slots (nreverse slots)
2355           defaults (nreverse defaults))
2356     (and predicate pred-form
2357          (progn (cl-push (list 'defsubst* predicate '(cl-x)
2358                                (if (eq (car pred-form) 'and)
2359                                    (append pred-form '(t))
2360                                  (list 'and pred-form t))) forms)
2361                 (cl-push (cons predicate 'error-free) side-eff)))
2362     (and copier
2363          (progn (cl-push (list 'defun copier '(x) '(copy-sequence x)) forms)
2364                 (cl-push (cons copier t) side-eff)))
2365     (if constructor
2366         (cl-push (list constructor
2367                        (cons '&key (delq nil (copy-sequence slots))))
2368                  constrs))
2369     (while constrs
2370       (let* ((name (caar constrs))
2371              (args (cadr (cl-pop constrs)))
2372              (anames (cl-arglist-args args))
2373              (make (mapcar* (function (lambda (s d) (if (memq s anames) s d)))
2374                             slots defaults)))
2375         (cl-push (list 'defsubst* name
2376                        (list* '&cl-defs (list 'quote (cons nil descs)) args)
2377                        (cons type make)) forms)
2378         (if (cl-safe-expr-p (cons 'progn (mapcar 'second descs)))
2379             (cl-push (cons name t) side-eff))))
2380     (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2381     (if print-func
2382         (cl-push (list 'push
2383                        (list 'function
2384                              (list 'lambda '(cl-x cl-s cl-n)
2385                                    (list 'and pred-form print-func)))
2386                        'custom-print-functions) forms))
2387     (cl-push (list 'setq tag-symbol (list 'list (list 'quote tag))) forms)
2388     (cl-push (list* 'eval-when '(compile load eval)
2389                     (list 'put (list 'quote name) '(quote cl-struct-slots)
2390                           (list 'quote descs))
2391                     (list 'put (list 'quote name) '(quote cl-struct-type)
2392                           (list 'quote (list type (eq named t))))
2393                     (list 'put (list 'quote name) '(quote cl-struct-include)
2394                           (list 'quote include))
2395                     (list 'put (list 'quote name) '(quote cl-struct-print)
2396                           print-auto)
2397                     (mapcar (function (lambda (x)
2398                                         (list 'put (list 'quote (car x))
2399                                               '(quote side-effect-free)
2400                                               (list 'quote (cdr x)))))
2401                             side-eff))
2402              forms)
2403     (cons 'progn (nreverse (cons (list 'quote name) forms)))))
2404
2405 ;;;###autoload
2406 (defun cl-struct-setf-expander (x name accessor pred-form pos)
2407   (let* ((temp (gensym "--x--")) (store (gensym "--store--")))
2408     (list (list temp) (list x) (list store)
2409           (append '(progn)
2410                   (and pred-form
2411                        (list (list 'or (subst temp 'cl-x pred-form)
2412                                    (list 'error
2413                                          (format
2414                                           "%s storing a non-%s" accessor name)
2415                                          temp))))
2416                   (list (if (eq (car (get name 'cl-struct-type)) 'vector)
2417                             (list 'aset temp pos store)
2418                           (list 'setcar
2419                                 (if (<= pos 5)
2420                                     (let ((xx temp))
2421                                       (while (>= (setq pos (1- pos)) 0)
2422                                         (setq xx (list 'cdr xx)))
2423                                       xx)
2424                                   (list 'nthcdr pos temp))
2425                                 store))))
2426           (list accessor temp))))
2427
2428
2429 ;;; Types and assertions.
2430
2431 ;;;###autoload
2432 (defmacro deftype (name args &rest body)
2433   "(deftype NAME ARGLIST BODY...): define NAME as a new data type.
2434 The type name can then be used in `typecase', `check-type', etc."
2435   (list 'eval-when '(compile load eval)
2436         (cl-transform-function-property
2437          name 'cl-deftype-handler (cons (list* '&cl-defs ''('*) args) body))))
2438
2439 (defun cl-make-type-test (val type)
2440   (if (symbolp type)
2441       (cond ((get type 'cl-deftype-handler)
2442              (cl-make-type-test val (funcall (get type 'cl-deftype-handler))))
2443             ((memq type '(nil t)) type)
2444             ((eq type 'string-char) (list 'characterp val))
2445             ((eq type 'null) (list 'null val))
2446             ((eq type 'float) (list 'floatp-safe val))
2447             ((eq type 'real) (list 'numberp val))
2448             ((eq type 'fixnum) (list 'integerp val))
2449             (t
2450              (let* ((name (symbol-name type))
2451                     (namep (intern (concat name "p"))))
2452                (if (fboundp namep) (list namep val)
2453                  (list (intern (concat name "-p")) val)))))
2454     (cond ((get (car type) 'cl-deftype-handler)
2455            (cl-make-type-test val (apply (get (car type) 'cl-deftype-handler)
2456                                          (cdr type))))
2457           ((memq (car-safe type) '(integer float real number))
2458            (delq t (list 'and (cl-make-type-test val (car type))
2459                          (if (memq (cadr type) '(* nil)) t
2460                            (if (consp (cadr type)) (list '> val (caadr type))
2461                              (list '>= val (cadr type))))
2462                          (if (memq (caddr type) '(* nil)) t
2463                            (if (consp (caddr type)) (list '< val (caaddr type))
2464                              (list '<= val (caddr type)))))))
2465           ((memq (car-safe type) '(and or not))
2466            (cons (car type)
2467                  (mapcar (function (lambda (x) (cl-make-type-test val x)))
2468                          (cdr type))))
2469           ((memq (car-safe type) '(member member*))
2470            (list 'and (list 'member* val (list 'quote (cdr type))) t))
2471           ((eq (car-safe type) 'satisfies) (list (cadr type) val))
2472           (t (error "Bad type spec: %s" type)))))
2473
2474 ;;;###autoload
2475 (defun typep (val type)   ; See compiler macro below.
2476   "Check that OBJECT is of type TYPE.
2477 TYPE is a Common Lisp-style type specifier."
2478   (eval (cl-make-type-test 'val type)))
2479
2480 ;;;###autoload
2481 (defmacro check-type (form type &optional string)
2482   "Verify that FORM is of type TYPE; signal an error if not.
2483 STRING is an optional description of the desired type."
2484   (and (or (not (cl-compiling-file))
2485            (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2486        (let* ((temp (if (cl-simple-expr-p form 3) form (gensym)))
2487               (body (list 'or (cl-make-type-test temp type)
2488                           (list 'signal '(quote wrong-type-argument)
2489                                 (list 'list (or string (list 'quote type))
2490                                       temp (list 'quote form))))))
2491          (if (eq temp form) (list 'progn body nil)
2492            (list 'let (list (list temp form)) body nil)))))
2493
2494 ;;;###autoload
2495 (defmacro assert (form &optional show-args string &rest args)
2496   "Verify that FORM returns non-nil; signal an error if not.
2497 Second arg SHOW-ARGS means to include arguments of FORM in message.
2498 Other args STRING and ARGS... are arguments to be passed to `error'.
2499 They are not evaluated unless the assertion fails.  If STRING is
2500 omitted, a default message listing FORM itself is used."
2501   (and (or (not (cl-compiling-file))
2502            (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2503        (let ((sargs (and show-args (delq nil (mapcar
2504                                               (function
2505                                                (lambda (x)
2506                                                  (and (not (cl-const-expr-p x))
2507                                                       x))) (cdr form))))))
2508          (list 'progn
2509                (list 'or form
2510                      (if string
2511                          (list* 'error string (append sargs args))
2512                        (list 'signal '(quote cl-assertion-failed)
2513                              (list* 'list (list 'quote form) sargs))))
2514                nil))))
2515
2516 ;;;###autoload
2517 (defmacro ignore-errors (&rest body)
2518   "Execute FORMS; if an error occurs, return nil.
2519 Otherwise, return result of last FORM."
2520   (list 'condition-case nil (cons 'progn body) '(error nil)))
2521
2522
2523 ;;; Some predicates for analyzing Lisp forms.  These are used by various
2524 ;;; macro expanders to optimize the results in certain common cases.
2525
2526 (defconst cl-simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
2527                             car-safe cdr-safe progn prog1 prog2))
2528 (defconst cl-safe-funcs '(* / % length memq list vector vectorp
2529                           < > <= >= = error))
2530
2531 ;;; Check if no side effects, and executes quickly.
2532 (defun cl-simple-expr-p (x &optional size)
2533   (or size (setq size 10))
2534   (if (and (consp x) (not (memq (car x) '(quote function function*))))
2535       (and (symbolp (car x))
2536            (or (memq (car x) cl-simple-funcs)
2537                (get (car x) 'side-effect-free))
2538            (progn
2539              (setq size (1- size))
2540              (while (and (setq x (cdr x))
2541                          (setq size (cl-simple-expr-p (car x) size))))
2542              (and (null x) (>= size 0) size)))
2543     (and (> size 0) (1- size))))
2544
2545 (defun cl-simple-exprs-p (xs)
2546   (while (and xs (cl-simple-expr-p (car xs)))
2547     (setq xs (cdr xs)))
2548   (not xs))
2549
2550 ;;; Check if no side effects.
2551 (defun cl-safe-expr-p (x)
2552   (or (not (and (consp x) (not (memq (car x) '(quote function function*)))))
2553       (and (symbolp (car x))
2554            (or (memq (car x) cl-simple-funcs)
2555                (memq (car x) cl-safe-funcs)
2556                (get (car x) 'side-effect-free))
2557            (progn
2558              (while (and (setq x (cdr x)) (cl-safe-expr-p (car x))))
2559              (null x)))))
2560
2561 ;;; Check if constant (i.e., no side effects or dependencies).
2562 (defun cl-const-expr-p (x)
2563   (cond ((consp x)
2564          (or (eq (car x) 'quote)
2565              (and (memq (car x) '(function function*))
2566                   (or (symbolp (nth 1 x))
2567                       (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
2568         ((symbolp x) (and (memq x '(nil t)) t))
2569         (t t)))
2570
2571 (defun cl-const-exprs-p (xs)
2572   (while (and xs (cl-const-expr-p (car xs)))
2573     (setq xs (cdr xs)))
2574   (not xs))
2575
2576 (defun cl-const-expr-val (x)
2577   (and (eq (cl-const-expr-p x) t) (if (consp x) (nth 1 x) x)))
2578
2579 (defun cl-expr-access-order (x v)
2580   (if (cl-const-expr-p x) v
2581     (if (consp x)
2582         (progn
2583           (while (setq x (cdr x)) (setq v (cl-expr-access-order (car x) v)))
2584           v)
2585       (if (eq x (car v)) (cdr v) '(t)))))
2586
2587 ;;; Count number of times X refers to Y.  Return NIL for 0 times.
2588 (defun cl-expr-contains (x y)
2589   (cond ((equal y x) 1)
2590         ((and (consp x) (not (memq (car-safe x) '(quote function function*))))
2591          (let ((sum 0))
2592            (while x
2593              (setq sum (+ sum (or (cl-expr-contains (cl-pop x) y) 0))))
2594            (and (> sum 0) sum)))
2595         (t nil)))
2596
2597 (defun cl-expr-contains-any (x y)
2598   (while (and y (not (cl-expr-contains x (car y)))) (cl-pop y))
2599   y)
2600
2601 ;;; Check whether X may depend on any of the symbols in Y.
2602 (defun cl-expr-depends-p (x y)
2603   (and (not (cl-const-expr-p x))
2604        (or (not (cl-safe-expr-p x)) (cl-expr-contains-any x y))))
2605
2606
2607 ;;; Compiler macros.
2608
2609 ;;;###autoload
2610 (defmacro define-compiler-macro (func args &rest body)
2611   "(define-compiler-macro FUNC ARGLIST BODY...): Define a compiler-only macro.
2612 This is like `defmacro', but macro expansion occurs only if the call to
2613 FUNC is compiled (i.e., not interpreted).  Compiler macros should be used
2614 for optimizing the way calls to FUNC are compiled; the form returned by
2615 BODY should do the same thing as a call to the normal function called
2616 FUNC, though possibly more efficiently.  Note that, like regular macros,
2617 compiler macros are expanded repeatedly until no further expansions are
2618 possible.  Unlike regular macros, BODY can decide to \"punt\" and leave the
2619 original function call alone by declaring an initial `&whole foo' parameter
2620 and then returning foo."
2621   (let ((p (if (listp args) args (list '&rest args))) (res nil))
2622     (while (consp p) (cl-push (cl-pop p) res))
2623     (setq args (nreverse res)) (setcdr res (and p (list '&rest p))))
2624   (list 'eval-when '(compile load eval)
2625         (cl-transform-function-property
2626          func 'cl-compiler-macro
2627          (cons (if (memq '&whole args) (delq '&whole args)
2628                  (cons '--cl-whole-arg-- args)) body))
2629         (list 'or (list 'get (list 'quote func) '(quote byte-compile))
2630               (list 'put (list 'quote func) '(quote byte-compile)
2631                     '(quote cl-byte-compile-compiler-macro)))))
2632
2633 ;;;###autoload
2634 (defun compiler-macroexpand (form)
2635   (while
2636       (let ((func (car-safe form)) (handler nil))
2637         (while (and (symbolp func)
2638                     (not (setq handler (get func 'cl-compiler-macro)))
2639                     (fboundp func)
2640                     (or (not (eq (car-safe (symbol-function func)) 'autoload))
2641                         (load (nth 1 (symbol-function func)))))
2642           (setq func (symbol-function func)))
2643         (and handler
2644              (not (eq form (setq form (apply handler form (cdr form))))))))
2645   form)
2646
2647 (defun cl-byte-compile-compiler-macro (form)
2648   (if (eq form (setq form (compiler-macroexpand form)))
2649       (byte-compile-normal-call form)
2650     (byte-compile-form form)))
2651
2652 (defmacro defsubst* (name args &rest body)
2653   "(defsubst* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
2654 Like `defun', except the function is automatically declared `inline',
2655 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2656 surrounded by (block NAME ...)."
2657   (let* ((argns (cl-arglist-args args)) (p argns)
2658          (pbody (cons 'progn body))
2659          (unsafe (not (cl-safe-expr-p pbody))))
2660     (while (and p (eq (cl-expr-contains args (car p)) 1)) (cl-pop p))
2661     (list 'progn
2662           (if p nil   ; give up if defaults refer to earlier args
2663             (list 'define-compiler-macro name
2664                   (list* '&whole 'cl-whole '&cl-quote args)
2665                   (list* 'cl-defsubst-expand (list 'quote argns)
2666                          (list 'quote (list* 'block name body))
2667                          (not (or unsafe (cl-expr-access-order pbody argns)))
2668                          (and (memq '&key args) 'cl-whole) unsafe argns)))
2669           (list* 'defun* name args body))))
2670
2671 (defun cl-defsubst-expand (argns body simple whole unsafe &rest argvs)
2672   (if (and whole (not (cl-safe-expr-p (cons 'progn argvs)))) whole
2673     (if (cl-simple-exprs-p argvs) (setq simple t))
2674     (let ((lets (delq nil
2675                       (mapcar* (function
2676                                 (lambda (argn argv)
2677                                   (if (or simple (cl-const-expr-p argv))
2678                                       (progn (setq body (subst argv argn body))
2679                                              (and unsafe (list argn argv)))
2680                                     (list argn argv))))
2681                                argns argvs))))
2682       (if lets (list 'let lets body) body))))
2683
2684
2685 ;;; Compile-time optimizations for some functions defined in this package.
2686 ;;; Note that cl.el arranges to force cl-macs to be loaded at compile-time,
2687 ;;; mainly to make sure these macros will be present.
2688
2689 (put 'eql 'byte-compile nil)
2690 (define-compiler-macro eql (&whole form a b)
2691   (cond ((eq (cl-const-expr-p a) t)
2692          (let ((val (cl-const-expr-val a)))
2693            (if (and (numberp val) (not (integerp val)))
2694                (list 'equal a b)
2695              (list 'eq a b))))
2696         ((eq (cl-const-expr-p b) t)
2697          (let ((val (cl-const-expr-val b)))
2698            (if (and (numberp val) (not (integerp val)))
2699                (list 'equal a b)
2700              (list 'eq a b))))
2701         ((cl-simple-expr-p a 5)
2702          (list 'if (list 'numberp a)
2703                (list 'equal a b)
2704                (list 'eq a b)))
2705         ((and (cl-safe-expr-p a)
2706               (cl-simple-expr-p b 5))
2707          (list 'if (list 'numberp b)
2708                (list 'equal a b)
2709                (list 'eq a b)))
2710         (t form)))
2711
2712 (define-compiler-macro member* (&whole form a list &rest keys)
2713   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
2714                    (cl-const-expr-val (nth 1 keys)))))
2715     (cond ((eq test 'eq) (list 'memq a list))
2716           ((eq test 'equal) (list 'member a list))
2717           ((or (null keys) (eq test 'eql))
2718            (if (eq (cl-const-expr-p a) t)
2719                (list (if (floatp-safe (cl-const-expr-val a)) 'member 'memq)
2720                      a list)
2721              (if (eq (cl-const-expr-p list) t)
2722                  (let ((p (cl-const-expr-val list)) (mb nil) (mq nil))
2723                    (if (not (cdr p))
2724                        (and p (list 'eql a (list 'quote (car p))))
2725                      (while p
2726                        (if (floatp-safe (car p)) (setq mb t)
2727                          (or (integerp (car p)) (symbolp (car p)) (setq mq t)))
2728                        (setq p (cdr p)))
2729                      (if (not mb) (list 'memq a list)
2730                        (if (not mq) (list 'member a list) form))))
2731                form)))
2732           (t form))))
2733
2734 (define-compiler-macro assoc* (&whole form a list &rest keys)
2735   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
2736                    (cl-const-expr-val (nth 1 keys)))))
2737     (cond ((eq test 'eq) (list 'assq a list))
2738           ((eq test 'equal) (list 'assoc a list))
2739           ((and (eq (cl-const-expr-p a) t) (or (null keys) (eq test 'eql)))
2740            (if (floatp-safe (cl-const-expr-val a))
2741                (list 'assoc a list) (list 'assq a list)))
2742           (t form))))
2743
2744 (define-compiler-macro adjoin (&whole form a list &rest keys)
2745   (if (and (cl-simple-expr-p a) (cl-simple-expr-p list)
2746            (not (memq ':key keys)))
2747       (list 'if (list* 'member* a list keys) list (list 'cons a list))
2748     form))
2749
2750 (define-compiler-macro list* (arg &rest others)
2751   (let* ((args (reverse (cons arg others)))
2752          (form (car args)))
2753     (while (setq args (cdr args))
2754       (setq form (list 'cons (car args) form)))
2755     form))
2756
2757 (define-compiler-macro get* (sym prop &optional def)
2758   (if def
2759       (list 'getf (list 'symbol-plist sym) prop def)
2760     (list 'get sym prop)))
2761
2762 (define-compiler-macro typep (&whole form val type)
2763   (if (cl-const-expr-p type)
2764       (let ((res (cl-make-type-test val (cl-const-expr-val type))))
2765         (if (or (memq (cl-expr-contains res val) '(nil 1))
2766                 (cl-simple-expr-p val)) res
2767           (let ((temp (gensym)))
2768             (list 'let (list (list temp val)) (subst temp val res)))))
2769     form))
2770
2771
2772 (mapcar (function
2773          (lambda (y)
2774            (put (car y) 'side-effect-free t)
2775            (put (car y) 'byte-compile 'cl-byte-compile-compiler-macro)
2776            (put (car y) 'cl-compiler-macro
2777                 (list 'lambda '(w x)
2778                       (if (symbolp (cadr y))
2779                           (list 'list (list 'quote (cadr y))
2780                                 (list 'list (list 'quote (caddr y)) 'x))
2781                         (cons 'list (cdr y)))))))
2782         '((first 'car x) (second 'cadr x) (third 'caddr x) (fourth 'cadddr x)
2783           (fifth 'nth 4 x) (sixth 'nth 5 x) (seventh 'nth 6 x)
2784           (eighth 'nth 7 x) (ninth 'nth 8 x) (tenth 'nth 9 x)
2785           (rest 'cdr x) (endp 'null x) (plusp '> x 0) (minusp '< x 0)
2786           (caar car car) (cadr car cdr) (cdar cdr car) (cddr cdr cdr)
2787           (caaar car caar) (caadr car cadr) (cadar car cdar)
2788           (caddr car cddr) (cdaar cdr caar) (cdadr cdr cadr)
2789           (cddar cdr cdar) (cdddr cdr cddr) (caaaar car caaar)
2790           (caaadr car caadr) (caadar car cadar) (caaddr car caddr)
2791           (cadaar car cdaar) (cadadr car cdadr) (caddar car cddar)
2792           (cadddr car cdddr) (cdaaar cdr caaar) (cdaadr cdr caadr)
2793           (cdadar cdr cadar) (cdaddr cdr caddr) (cddaar cdr cdaar)
2794           (cddadr cdr cdadr) (cdddar cdr cddar) (cddddr cdr cdddr) ))
2795
2796 ;;; Things that are inline.
2797 (proclaim '(inline floatp-safe acons map concatenate notany notevery
2798 ;; XEmacs change
2799                    cl-set-elt revappend nreconc))
2800
2801 ;;; Things that are side-effect-free.
2802 (mapcar (function (lambda (x) (put x 'side-effect-free t)))
2803         '(oddp evenp abs expt signum last butlast ldiff pairlis gcd lcm
2804           isqrt floor* ceiling* truncate* round* mod* rem* subseq
2805           list-length get* getf gethash hash-table-count))
2806
2807 ;;; Things that are side-effect-and-error-free.
2808 (mapcar (function (lambda (x) (put x 'side-effect-free 'error-free)))
2809         '(eql floatp-safe list* subst acons equalp random-state-p
2810           copy-tree sublis hash-table-p))
2811
2812
2813 (run-hooks 'cl-macs-load-hook)
2814
2815 ;;; cl-macs.el ends here