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