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