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