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