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