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