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