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