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