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