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