Merge branch 'master' into comment-cache
[emacs.git] / lisp / emacs-lisp / cl-macs.el
blob40342f3fe48d60fff1b86b8e66a805f32119f8a0
1 ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993, 2001-2017 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 0)
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 (help--docstring-quote
302 (let ((print-gensym nil) (print-quoted t)
303 (print-escape-newlines t))
304 (format "%S" (cons 'fn (cl--make-usage-args
305 orig-args))))))
306 header)))
307 ;; FIXME: we'd want to choose an arg name for the &rest param
308 ;; and pass that as `expr' to cl--do-arglist, but that ends up
309 ;; generating code with a redundant let-binding, so we instead
310 ;; pass a dummy and then look in cl--bind-lets to find what var
311 ;; this was bound to.
312 (cl--do-arglist args :dummy slen)
313 (setq cl--bind-lets (nreverse cl--bind-lets))
314 ;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
315 (list '&rest (car (pop cl--bind-lets))))))))
316 `(nil
317 (,@(nreverse simple-args) ,@rest-args)
318 ,@header
319 ,(macroexp-let* cl--bind-lets
320 (macroexp-progn
321 `(,@(nreverse cl--bind-forms)
322 ,@body)))))))
324 ;;;###autoload
325 (defmacro cl-defun (name args &rest body)
326 "Define NAME as a function.
327 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
328 and BODY is implicitly surrounded by (cl-block NAME ...).
330 The full form of a Common Lisp function argument list is
332 (VAR...
333 [&optional (VAR [INITFORM [SVAR]])...]
334 [&rest|&body VAR]
335 [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
336 [&aux (VAR [INITFORM])...])
338 VAR maybe be replaced recursively with an argument list for
339 destructing, `&whole' is supported within these sublists. If
340 SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
341 written simply `VAR'. See the Info node `(cl)Argument Lists' for
342 more details.
344 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
345 (declare (debug
346 ;; Same as defun but use cl-lambda-list.
347 (&define [&or name ("setf" :name setf name)]
348 cl-lambda-list
349 cl-declarations-or-string
350 [&optional ("interactive" interactive)]
351 def-body))
352 (doc-string 3)
353 (indent 2))
354 (let* ((res (cl--transform-lambda (cons args body) name))
355 (form `(defun ,name ,@(cdr res))))
356 (if (car res) `(progn ,(car res) ,form) form)))
358 ;;;###autoload
359 (defmacro cl-iter-defun (name args &rest body)
360 "Define NAME as a generator function.
361 Like normal `iter-defun', except ARGLIST allows full Common Lisp conventions,
362 and BODY is implicitly surrounded by (cl-block NAME ...).
364 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
365 (declare (debug
366 ;; Same as iter-defun but use cl-lambda-list.
367 (&define [&or name ("setf" :name setf name)]
368 cl-lambda-list
369 cl-declarations-or-string
370 [&optional ("interactive" interactive)]
371 def-body))
372 (doc-string 3)
373 (indent 2))
374 (require 'generator)
375 (let* ((res (cl--transform-lambda (cons args body) name))
376 (form `(iter-defun ,name ,@(cdr res))))
377 (if (car res) `(progn ,(car res) ,form) form)))
379 ;; The lambda list for macros is different from that of normal lambdas.
380 ;; Note that &environment is only allowed as first or last items in the
381 ;; top level list.
383 (def-edebug-spec cl-macro-list
384 (([&optional "&environment" arg]
385 [&rest cl-macro-arg]
386 [&optional ["&optional" &rest
387 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
388 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
389 [&optional ["&key" [&rest
390 [&or ([&or (symbolp cl-macro-arg) arg]
391 &optional def-form cl-macro-arg)
392 arg]]
393 &optional "&allow-other-keys"]]
394 [&optional ["&aux" &rest
395 &or (symbolp &optional def-form) symbolp]]
396 [&optional "&environment" arg]
399 (def-edebug-spec cl-macro-arg
400 (&or arg cl-macro-list1))
402 (def-edebug-spec cl-macro-list1
403 (([&optional "&whole" arg] ;; only allowed at lower levels
404 [&rest cl-macro-arg]
405 [&optional ["&optional" &rest
406 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
407 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
408 [&optional ["&key" [&rest
409 [&or ([&or (symbolp cl-macro-arg) arg]
410 &optional def-form cl-macro-arg)
411 arg]]
412 &optional "&allow-other-keys"]]
413 [&optional ["&aux" &rest
414 &or (symbolp &optional def-form) symbolp]]
415 . [&or arg nil])))
417 ;;;###autoload
418 (defmacro cl-defmacro (name args &rest body)
419 "Define NAME as a macro.
420 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
421 and BODY is implicitly surrounded by (cl-block NAME ...).
423 The full form of a Common Lisp macro argument list is
425 (VAR...
426 [&optional (VAR [INITFORM [SVAR]])...]
427 [&rest|&body VAR]
428 [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
429 [&aux (VAR [INITFORM])...]
430 [&environment VAR])
432 VAR maybe be replaced recursively with an argument list for
433 destructing, `&whole' is supported within these sublists. If
434 SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
435 written simply `VAR'. See the Info node `(cl)Argument Lists' for
436 more details.
438 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
439 (declare (debug
440 (&define name cl-macro-list cl-declarations-or-string def-body))
441 (doc-string 3)
442 (indent 2))
443 (let* ((res (cl--transform-lambda (cons args body) name))
444 (form `(defmacro ,name ,@(cdr res))))
445 (if (car res) `(progn ,(car res) ,form) form)))
447 (def-edebug-spec cl-lambda-expr
448 (&define ("lambda" cl-lambda-list
449 ;;cl-declarations-or-string
450 ;;[&optional ("interactive" interactive)]
451 def-body)))
453 ;; Redefine function-form to also match cl-function
454 (def-edebug-spec function-form
455 ;; form at the end could also handle "function",
456 ;; but recognize it specially to avoid wrapping function forms.
457 (&or ([&or "quote" "function"] &or symbolp lambda-expr)
458 ("cl-function" cl-function)
459 form))
461 ;;;###autoload
462 (defmacro cl-function (func)
463 "Introduce a function.
464 Like normal `function', except that if argument is a lambda form,
465 its argument list allows full Common Lisp conventions."
466 (declare (debug (&or symbolp cl-lambda-expr)))
467 (if (eq (car-safe func) 'lambda)
468 (let* ((res (cl--transform-lambda (cdr func) 'cl-none))
469 (form `(function (lambda . ,(cdr res)))))
470 (if (car res) `(progn ,(car res) ,form) form))
471 `(function ,func)))
473 (defun cl--make-usage-var (x)
474 "X can be a var or a (destructuring) lambda-list."
475 (cond
476 ((symbolp x) (make-symbol (upcase (symbol-name x))))
477 ((consp x) (cl--make-usage-args x))
478 (t x)))
480 (defun cl--make-usage-args (arglist)
481 (let ((aux (ignore-errors (cl-position '&aux arglist))))
482 (when aux
483 ;; `&aux' args aren't arguments, so let's just drop them from the
484 ;; usage info.
485 (setq arglist (cl-subseq arglist 0 aux))))
486 (if (cdr-safe (last arglist)) ;Not a proper list.
487 (let* ((last (last arglist))
488 (tail (cdr last)))
489 (unwind-protect
490 (progn
491 (setcdr last nil)
492 (nconc (cl--make-usage-args arglist) (cl--make-usage-var tail)))
493 (setcdr last tail)))
494 ;; `orig-args' can contain &cl-defs.
495 (let ((x (memq '&cl-defs arglist)))
496 (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
497 (let ((state nil))
498 (mapcar (lambda (x)
499 (cond
500 ((symbolp x)
501 (let ((first (aref (symbol-name x) 0)))
502 (if (eq ?\& first)
503 (setq state x)
504 ;; Strip a leading underscore, since it only
505 ;; means that this argument is unused.
506 (make-symbol (upcase (if (eq ?_ first)
507 (substring (symbol-name x) 1)
508 (symbol-name x)))))))
509 ((not (consp x)) x)
510 ((memq state '(nil &rest)) (cl--make-usage-args x))
511 (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
512 (cl-list*
513 (if (and (consp (car x)) (eq state '&key))
514 (list (caar x) (cl--make-usage-var (nth 1 (car x))))
515 (cl--make-usage-var (car x)))
516 (nth 1 x) ;INITFORM.
517 (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
518 ))))
519 arglist))))
521 (defun cl--do-&aux (args)
522 (while (and (eq (car args) '&aux) (pop args))
523 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
524 (if (consp (car args))
525 (if (and cl--bind-enquote (cl-cadar args))
526 (cl--do-arglist (caar args)
527 `',(cadr (pop args)))
528 (cl--do-arglist (caar args) (cadr (pop args))))
529 (cl--do-arglist (pop args) nil))))
530 (if args (error "Malformed argument list ends with: %S" args)))
532 (defun cl--do-arglist (args expr &optional num) ; uses cl--bind-*
533 (if (nlistp args)
534 (if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
535 (error "Invalid argument name: %s" args)
536 (push (list args expr) cl--bind-lets))
537 (setq args (cl-copy-list args))
538 (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
539 (let ((p (memq '&body args))) (if p (setcar p '&rest)))
540 (if (memq '&environment args) (error "&environment used incorrectly"))
541 (let ((restarg (memq '&rest args))
542 (safety (if (cl--compiling-file) cl--optimize-safety 3))
543 (keys nil)
544 (laterarg nil) (exactarg nil) minarg)
545 (or num (setq num 0))
546 (setq restarg (if (listp (cadr restarg))
547 (make-symbol "--cl-rest--")
548 (cadr restarg)))
549 (push (list restarg expr) cl--bind-lets)
550 (if (eq (car args) '&whole)
551 (push (list (cl--pop2 args) restarg) cl--bind-lets))
552 (let ((p args))
553 (setq minarg restarg)
554 (while (and p (not (memq (car p) cl--lambda-list-keywords)))
555 (or (eq p args) (setq minarg (list 'cdr minarg)))
556 (setq p (cdr p)))
557 (if (memq (car p) '(nil &aux))
558 (setq minarg `(= (length ,restarg)
559 ,(length (cl-ldiff args p)))
560 exactarg (not (eq args p)))))
561 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
562 (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
563 restarg)))
564 (cl--do-arglist
565 (pop args)
566 (if (or laterarg (= safety 0)) poparg
567 `(if ,minarg ,poparg
568 (signal 'wrong-number-of-arguments
569 (list ,(and (not (eq cl--bind-block 'cl-none))
570 `',cl--bind-block)
571 (length ,restarg)))))))
572 (setq num (1+ num) laterarg t))
573 (while (and (eq (car args) '&optional) (pop args))
574 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
575 (let ((arg (pop args)))
576 (or (consp arg) (setq arg (list arg)))
577 (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
578 (let ((def (if (cdr arg) (nth 1 arg)
579 (or (car cl--bind-defs)
580 (nth 1 (assq (car arg) cl--bind-defs)))))
581 (poparg `(pop ,restarg)))
582 (and def cl--bind-enquote (setq def `',def))
583 (cl--do-arglist (car arg)
584 (if def `(if ,restarg ,poparg ,def) poparg))
585 (setq num (1+ num))))))
586 (if (eq (car args) '&rest)
587 (let ((arg (cl--pop2 args)))
588 (if (consp arg) (cl--do-arglist arg restarg)))
589 (or (eq (car args) '&key) (= safety 0) exactarg
590 (push `(if ,restarg
591 (signal 'wrong-number-of-arguments
592 (list
593 ,(and (not (eq cl--bind-block 'cl-none))
594 `',cl--bind-block)
595 (+ ,num (length ,restarg)))))
596 cl--bind-forms)))
597 (while (and (eq (car args) '&key) (pop args))
598 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
599 (let ((arg (pop args)))
600 (or (consp arg) (setq arg (list arg)))
601 (let* ((karg (if (consp (car arg)) (caar arg)
602 (let ((name (symbol-name (car arg))))
603 ;; Strip a leading underscore, since it only
604 ;; means that this argument is unused, but
605 ;; shouldn't affect the key's name (bug#12367).
606 (if (eq ?_ (aref name 0))
607 (setq name (substring name 1)))
608 (intern (format ":%s" name)))))
609 (varg (if (consp (car arg)) (cl-cadar arg) (car arg)))
610 (def (if (cdr arg) (cadr arg)
611 ;; The ordering between those two or clauses is
612 ;; irrelevant, since in practice only one of the two
613 ;; is ever non-nil (the car is only used for
614 ;; cl-deftype which doesn't use the cdr).
615 (or (car cl--bind-defs)
616 (cadr (assq varg cl--bind-defs)))))
617 (look `(plist-member ,restarg ',karg)))
618 (and def cl--bind-enquote (setq def `',def))
619 (if (cddr arg)
620 (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
621 (val `(car (cdr ,temp))))
622 (cl--do-arglist temp look)
623 (cl--do-arglist varg
624 `(if ,temp
625 (prog1 ,val (setq ,temp t))
626 ,def)))
627 (cl--do-arglist
628 varg
629 `(car (cdr ,(if (null def)
630 look
631 `(or ,look
632 ,(if (eq (cl--const-expr-p def) t)
633 `'(nil ,(cl--const-expr-val def))
634 `(list nil ,def))))))))
635 (push karg keys)))))
636 (setq keys (nreverse keys))
637 (or (and (eq (car args) '&allow-other-keys) (pop args))
638 (null keys) (= safety 0)
639 (let* ((var (make-symbol "--cl-keys--"))
640 (allow '(:allow-other-keys))
641 (check `(while ,var
642 (cond
643 ((memq (car ,var) ',(append keys allow))
644 (setq ,var (cdr (cdr ,var))))
645 ((car (cdr (memq (quote ,@allow) ,restarg)))
646 (setq ,var nil))
648 (error
649 ,(format "Keyword argument %%s not one of %s"
650 keys)
651 (car ,var)))))))
652 (push `(let ((,var ,restarg)) ,check) cl--bind-forms)))
653 (cl--do-&aux args)
654 nil)))
656 (defun cl--arglist-args (args)
657 (if (nlistp args) (list args)
658 (let ((res nil) (kind nil) arg)
659 (while (consp args)
660 (setq arg (pop args))
661 (if (memq arg cl--lambda-list-keywords) (setq kind arg)
662 (if (eq arg '&cl-defs) (pop args)
663 (and (consp arg) kind (setq arg (car arg)))
664 (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
665 (setq res (nconc res (cl--arglist-args arg))))))
666 (nconc res (and args (list args))))))
668 ;;;###autoload
669 (defmacro cl-destructuring-bind (args expr &rest body)
670 "Bind the variables in ARGS to the result of EXPR and execute BODY."
671 (declare (indent 2)
672 (debug (&define cl-macro-list def-form cl-declarations def-body)))
673 (let* ((cl--bind-lets nil) (cl--bind-forms nil)
674 (cl--bind-defs nil) (cl--bind-block 'cl-none) (cl--bind-enquote nil))
675 (cl--do-arglist (or args '(&aux)) expr)
676 (macroexp-let* (nreverse cl--bind-lets)
677 (macroexp-progn (append (nreverse cl--bind-forms) body)))))
680 ;;; The `cl-eval-when' form.
682 (defvar cl--not-toplevel nil)
684 ;;;###autoload
685 (defmacro cl-eval-when (when &rest body)
686 "Control when BODY is evaluated.
687 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
688 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
689 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
691 \(fn (WHEN...) BODY...)"
692 (declare (indent 1) (debug (sexp body)))
693 (if (and (fboundp 'cl--compiling-file) (cl--compiling-file)
694 (not cl--not-toplevel) (not (boundp 'for-effect))) ;Horrible kludge.
695 (let ((comp (or (memq 'compile when) (memq :compile-toplevel when)))
696 (cl--not-toplevel t))
697 (if (or (memq 'load when) (memq :load-toplevel when))
698 (if comp (cons 'progn (mapcar 'cl--compile-time-too body))
699 `(if nil nil ,@body))
700 (progn (if comp (eval (cons 'progn body))) nil)))
701 (and (or (memq 'eval when) (memq :execute when))
702 (cons 'progn body))))
704 (defun cl--compile-time-too (form)
705 (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
706 (setq form (macroexpand
707 form (cons '(cl-eval-when) byte-compile-macro-environment))))
708 (cond ((eq (car-safe form) 'progn)
709 (cons 'progn (mapcar 'cl--compile-time-too (cdr form))))
710 ((eq (car-safe form) 'cl-eval-when)
711 (let ((when (nth 1 form)))
712 (if (or (memq 'eval when) (memq :execute when))
713 `(cl-eval-when (compile ,@when) ,@(cddr form))
714 form)))
715 (t (eval form) form)))
717 ;;;###autoload
718 (defmacro cl-load-time-value (form &optional _read-only)
719 "Like `progn', but evaluates the body at load time.
720 The result of the body appears to the compiler as a quoted constant."
721 (declare (debug (form &optional sexp)))
722 (if (cl--compiling-file)
723 (let* ((temp (cl-gentemp "--cl-load-time--"))
724 (set `(setq ,temp ,form)))
725 (if (and (fboundp 'byte-compile-file-form-defmumble)
726 (boundp 'this-kind) (boundp 'that-one))
727 ;; Else, we can't output right away, so we have to delay it to the
728 ;; next time we're at the top-level.
729 ;; FIXME: Use advice-add/remove.
730 (fset 'byte-compile-file-form
731 (let ((old (symbol-function 'byte-compile-file-form)))
732 (lambda (form)
733 (fset 'byte-compile-file-form old)
734 (byte-compile-file-form set)
735 (byte-compile-file-form form))))
736 ;; If we're not in the middle of compiling something, we can
737 ;; output directly to byte-compile-outbuffer, to make sure
738 ;; temp is set before we use it.
739 (print set byte-compile--outbuffer))
740 temp)
741 `',(eval form)))
744 ;;; Conditional control structures.
746 ;;;###autoload
747 (defmacro cl-case (expr &rest clauses)
748 "Eval EXPR and choose among clauses on that value.
749 Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
750 against each key in each KEYLIST; the corresponding BODY is evaluated.
751 If no clause succeeds, cl-case returns nil. A single atom may be used in
752 place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
753 allowed only in the final clause, and matches if no other keys match.
754 Key values are compared by `eql'.
755 \n(fn EXPR (KEYLIST BODY...)...)"
756 (declare (indent 1) (debug (form &rest (sexp body))))
757 (macroexp-let2 macroexp-copyable-p temp expr
758 (let* ((head-list nil))
759 `(cond
760 ,@(mapcar
761 (lambda (c)
762 (cons (cond ((memq (car c) '(t otherwise)) t)
763 ((eq (car c) 'cl--ecase-error-flag)
764 `(error "cl-ecase failed: %s, %s"
765 ,temp ',(reverse head-list)))
766 ((listp (car c))
767 (setq head-list (append (car c) head-list))
768 `(cl-member ,temp ',(car c)))
770 (if (memq (car c) head-list)
771 (error "Duplicate key in case: %s"
772 (car c)))
773 (push (car c) head-list)
774 `(eql ,temp ',(car c))))
775 (or (cdr c) '(nil))))
776 clauses)))))
778 ;;;###autoload
779 (defmacro cl-ecase (expr &rest clauses)
780 "Like `cl-case', but error if no case fits.
781 `otherwise'-clauses are not allowed.
782 \n(fn EXPR (KEYLIST BODY...)...)"
783 (declare (indent 1) (debug cl-case))
784 `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
786 ;;;###autoload
787 (defmacro cl-typecase (expr &rest clauses)
788 "Evals EXPR, chooses among clauses on that value.
789 Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
790 satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
791 cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
792 final clause, and matches if no other keys match.
793 \n(fn EXPR (TYPE BODY...)...)"
794 (declare (indent 1)
795 (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
796 (macroexp-let2 macroexp-copyable-p temp expr
797 (let* ((type-list nil))
798 (cons
799 'cond
800 (mapcar
801 (function
802 (lambda (c)
803 (cons (cond ((eq (car c) 'otherwise) t)
804 ((eq (car c) 'cl--ecase-error-flag)
805 `(error "cl-etypecase failed: %s, %s"
806 ,temp ',(reverse type-list)))
808 (push (car c) type-list)
809 `(cl-typep ,temp ',(car c))))
810 (or (cdr c) '(nil)))))
811 clauses)))))
813 ;;;###autoload
814 (defmacro cl-etypecase (expr &rest clauses)
815 "Like `cl-typecase', but error if no case fits.
816 `otherwise'-clauses are not allowed.
817 \n(fn EXPR (TYPE BODY...)...)"
818 (declare (indent 1) (debug cl-typecase))
819 `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
822 ;;; Blocks and exits.
824 ;;;###autoload
825 (defmacro cl-block (name &rest body)
826 "Define a lexically-scoped block named NAME.
827 NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
828 to jump prematurely out of the block. This differs from `catch' and `throw'
829 in two respects: First, the NAME is an unevaluated symbol rather than a
830 quoted symbol or other form; and second, NAME is lexically rather than
831 dynamically scoped: Only references to it within BODY will work. These
832 references may appear inside macro expansions, but not inside functions
833 called from BODY."
834 (declare (indent 1) (debug (symbolp body)))
835 (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
836 `(cl--block-wrapper
837 (catch ',(intern (format "--cl-block-%s--" name))
838 ,@body))))
840 ;;;###autoload
841 (defmacro cl-return (&optional result)
842 "Return from the block named nil.
843 This is equivalent to `(cl-return-from nil RESULT)'."
844 (declare (debug (&optional form)))
845 `(cl-return-from nil ,result))
847 ;;;###autoload
848 (defmacro cl-return-from (name &optional result)
849 "Return from the block named NAME.
850 This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
851 returning RESULT from that form (or nil if RESULT is omitted).
852 This is compatible with Common Lisp, but note that `defun' and
853 `defmacro' do not create implicit blocks as they do in Common Lisp."
854 (declare (indent 1) (debug (symbolp &optional form)))
855 (let ((name2 (intern (format "--cl-block-%s--" name))))
856 `(cl--block-throw ',name2 ,result)))
859 ;;; The "cl-loop" macro.
861 (defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
862 (defvar cl--loop-bindings) (defvar cl--loop-body)
863 (defvar cl--loop-finally)
864 (defvar cl--loop-finish-flag) ;Symbol set to nil to exit the loop?
865 (defvar cl--loop-first-flag)
866 (defvar cl--loop-initially) (defvar cl--loop-iterator-function)
867 (defvar cl--loop-name)
868 (defvar cl--loop-result) (defvar cl--loop-result-explicit)
869 (defvar cl--loop-result-var) (defvar cl--loop-steps)
870 (defvar cl--loop-symbol-macs)
872 (defun cl--loop-set-iterator-function (kind iterator)
873 (if cl--loop-iterator-function
874 ;; FIXME: Of course, we could make it work, but why bother.
875 (error "Iteration on %S does not support this combination" kind)
876 (setq cl--loop-iterator-function iterator)))
878 ;;;###autoload
879 (defmacro cl-loop (&rest loop-args)
880 "The Common Lisp `loop' macro.
881 Valid clauses include:
882 For clauses:
883 for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2 [by EXPR3]
884 for VAR = EXPR1 then EXPR2
885 for VAR in/on/in-ref LIST [by FUNC]
886 for VAR across/across-ref ARRAY
887 for VAR being:
888 the elements of/of-ref SEQUENCE [using (index VAR2)]
889 the symbols [of OBARRAY]
890 the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
891 the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
892 the overlays/intervals [of BUFFER] [from POS1] [to POS2]
893 the frames/buffers
894 the windows [of FRAME]
895 Iteration clauses:
896 repeat INTEGER
897 while/until/always/never/thereis CONDITION
898 Accumulation clauses:
899 collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
900 [into VAR]
901 Miscellaneous clauses:
902 with VAR = INIT
903 if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
904 named NAME
905 initially/finally [do] EXPRS...
906 do EXPRS...
907 [finally] return EXPR
909 For more details, see Info node `(cl)Loop Facility'.
911 \(fn CLAUSE...)"
912 (declare (debug (&rest &or
913 ;; These are usually followed by a symbol, but it can
914 ;; actually be any destructuring-bind pattern, which
915 ;; would erroneously match `form'.
916 [[&or "for" "as" "with" "and"] sexp]
917 ;; These are followed by expressions which could
918 ;; erroneously match `symbolp'.
919 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
920 "above" "below" "by" "in" "on" "=" "across"
921 "repeat" "while" "until" "always" "never"
922 "thereis" "collect" "append" "nconc" "sum"
923 "count" "maximize" "minimize" "if" "unless"
924 "return"]
925 form]
926 ["using" (symbolp symbolp)]
927 ;; Simple default, which covers 99% of the cases.
928 symbolp form)))
929 (if (not (memq t (mapcar #'symbolp
930 (delq nil (delq t (cl-copy-list loop-args))))))
931 `(cl-block nil (while t ,@loop-args))
932 (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
933 (cl--loop-body nil) (cl--loop-steps nil)
934 (cl--loop-result nil) (cl--loop-result-explicit nil)
935 (cl--loop-result-var nil) (cl--loop-finish-flag nil)
936 (cl--loop-accum-var nil) (cl--loop-accum-vars nil)
937 (cl--loop-initially nil) (cl--loop-finally nil)
938 (cl--loop-iterator-function nil) (cl--loop-first-flag nil)
939 (cl--loop-symbol-macs nil))
940 ;; Here is more or less how those dynbind vars are used after looping
941 ;; over cl--parse-loop-clause:
943 ;; (cl-block ,cl--loop-name
944 ;; (cl-symbol-macrolet ,cl--loop-symbol-macs
945 ;; (foldl #'cl--loop-let
946 ;; `((,cl--loop-result-var)
947 ;; ((,cl--loop-first-flag t))
948 ;; ((,cl--loop-finish-flag t))
949 ;; ,@cl--loop-bindings)
950 ;; ,@(nreverse cl--loop-initially)
951 ;; (while ;(well: cl--loop-iterator-function)
952 ;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
953 ;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
954 ;; ,@(nreverse cl--loop-steps)
955 ;; (setq ,cl--loop-first-flag nil))
956 ;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
957 ;; ,cl--loop-result-var
958 ;; ,@(nreverse cl--loop-finally)
959 ;; ,(or cl--loop-result-explicit
960 ;; cl--loop-result)))))
962 (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
963 (while (not (eq (car cl--loop-args) 'cl-end-loop))
964 (cl--parse-loop-clause))
965 (if cl--loop-finish-flag
966 (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
967 (if cl--loop-first-flag
968 (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
969 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
970 (let* ((epilogue (nconc (nreverse cl--loop-finally)
971 (list (or cl--loop-result-explicit
972 cl--loop-result))))
973 (ands (cl--loop-build-ands (nreverse cl--loop-body)))
974 (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
975 (body (append
976 (nreverse cl--loop-initially)
977 (list (if cl--loop-iterator-function
978 `(cl-block --cl-finish--
979 ,(funcall cl--loop-iterator-function
980 (if (eq (car ands) t) while-body
981 (cons `(or ,(car ands)
982 (cl-return-from
983 --cl-finish--
984 nil))
985 while-body))))
986 `(while ,(car ands) ,@while-body)))
987 (if cl--loop-finish-flag
988 (if (equal epilogue '(nil)) (list cl--loop-result-var)
989 `((if ,cl--loop-finish-flag
990 (progn ,@epilogue) ,cl--loop-result-var)))
991 epilogue))))
992 (if cl--loop-result-var
993 (push (list cl--loop-result-var) cl--loop-bindings))
994 (while cl--loop-bindings
995 (if (cdar cl--loop-bindings)
996 (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
997 (let ((lets nil))
998 (while (and cl--loop-bindings
999 (not (cdar cl--loop-bindings)))
1000 (push (car (pop cl--loop-bindings)) lets))
1001 (setq body (list (cl--loop-let lets body nil))))))
1002 (if cl--loop-symbol-macs
1003 (setq body
1004 (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
1005 `(cl-block ,cl--loop-name ,@body)))))
1007 ;; Below is a complete spec for cl-loop, in several parts that correspond
1008 ;; to the syntax given in CLtL2. The specs do more than specify where
1009 ;; the forms are; it also specifies, as much as Edebug allows, all the
1010 ;; syntactically valid cl-loop clauses. The disadvantage of this
1011 ;; completeness is rigidity, but the "for ... being" clause allows
1012 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
1014 ;; (def-edebug-spec cl-loop
1015 ;; ([&optional ["named" symbolp]]
1016 ;; [&rest
1017 ;; &or
1018 ;; ["repeat" form]
1019 ;; loop-for-as
1020 ;; loop-with
1021 ;; loop-initial-final]
1022 ;; [&rest loop-clause]
1023 ;; ))
1025 ;; (def-edebug-spec loop-with
1026 ;; ("with" loop-var
1027 ;; loop-type-spec
1028 ;; [&optional ["=" form]]
1029 ;; &rest ["and" loop-var
1030 ;; loop-type-spec
1031 ;; [&optional ["=" form]]]))
1033 ;; (def-edebug-spec loop-for-as
1034 ;; ([&or "for" "as"] loop-for-as-subclause
1035 ;; &rest ["and" loop-for-as-subclause]))
1037 ;; (def-edebug-spec loop-for-as-subclause
1038 ;; (loop-var
1039 ;; loop-type-spec
1040 ;; &or
1041 ;; [[&or "in" "on" "in-ref" "across-ref"]
1042 ;; form &optional ["by" function-form]]
1044 ;; ["=" form &optional ["then" form]]
1045 ;; ["across" form]
1046 ;; ["being"
1047 ;; [&or "the" "each"]
1048 ;; &or
1049 ;; [[&or "element" "elements"]
1050 ;; [&or "of" "in" "of-ref"] form
1051 ;; &optional "using" ["index" symbolp]];; is this right?
1052 ;; [[&or "hash-key" "hash-keys"
1053 ;; "hash-value" "hash-values"]
1054 ;; [&or "of" "in"]
1055 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
1056 ;; "hash-key" "hash-keys"] sexp)]]
1058 ;; [[&or "symbol" "present-symbol" "external-symbol"
1059 ;; "symbols" "present-symbols" "external-symbols"]
1060 ;; [&or "in" "of"] package-p]
1062 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
1063 ;; [[&or "frame" "frames"
1064 ;; "screen" "screens"
1065 ;; "buffer" "buffers"]]
1067 ;; [[&or "window" "windows"]
1068 ;; [&or "of" "in"] form]
1070 ;; [[&or "overlay" "overlays"
1071 ;; "extent" "extents"]
1072 ;; [&or "of" "in"] form
1073 ;; &optional [[&or "from" "to"] form]]
1075 ;; [[&or "interval" "intervals"]
1076 ;; [&or "in" "of"] form
1077 ;; &optional [[&or "from" "to"] form]
1078 ;; ["property" form]]
1080 ;; [[&or "key-code" "key-codes"
1081 ;; "key-seq" "key-seqs"
1082 ;; "key-binding" "key-bindings"]
1083 ;; [&or "in" "of"] form
1084 ;; &optional ["using" ([&or "key-code" "key-codes"
1085 ;; "key-seq" "key-seqs"
1086 ;; "key-binding" "key-bindings"]
1087 ;; sexp)]]
1088 ;; ;; For arbitrary extensions, recognize anything else.
1089 ;; [symbolp &rest &or symbolp form]
1090 ;; ]
1092 ;; ;; arithmetic - must be last since all parts are optional.
1093 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
1094 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
1095 ;; [&optional ["by" form]]
1096 ;; ]))
1098 ;; (def-edebug-spec loop-initial-final
1099 ;; (&or ["initially"
1100 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
1101 ;; &rest loop-non-atomic-expr]
1102 ;; ["finally" &or
1103 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
1104 ;; ["return" form]]))
1106 ;; (def-edebug-spec loop-and-clause
1107 ;; (loop-clause &rest ["and" loop-clause]))
1109 ;; (def-edebug-spec loop-clause
1110 ;; (&or
1111 ;; [[&or "while" "until" "always" "never" "thereis"] form]
1113 ;; [[&or "collect" "collecting"
1114 ;; "append" "appending"
1115 ;; "nconc" "nconcing"
1116 ;; "concat" "vconcat"] form
1117 ;; [&optional ["into" loop-var]]]
1119 ;; [[&or "count" "counting"
1120 ;; "sum" "summing"
1121 ;; "maximize" "maximizing"
1122 ;; "minimize" "minimizing"] form
1123 ;; [&optional ["into" loop-var]]
1124 ;; loop-type-spec]
1126 ;; [[&or "if" "when" "unless"]
1127 ;; form loop-and-clause
1128 ;; [&optional ["else" loop-and-clause]]
1129 ;; [&optional "end"]]
1131 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
1133 ;; ["return" form]
1134 ;; loop-initial-final
1135 ;; ))
1137 ;; (def-edebug-spec loop-non-atomic-expr
1138 ;; ([&not atom] form))
1140 ;; (def-edebug-spec loop-var
1141 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
1142 ;; ;; loop-var =>
1143 ;; ;; (loop-var . [&or nil loop-var])
1144 ;; ;; (symbolp . [&or nil loop-var])
1145 ;; ;; (symbolp . loop-var)
1146 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
1147 ;; ;; (symbolp . (symbolp . loop-var))
1148 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
1149 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
1151 ;; (def-edebug-spec loop-type-spec
1152 ;; (&optional ["of-type" loop-d-type-spec]))
1154 ;; (def-edebug-spec loop-d-type-spec
1155 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
1159 (defun cl--parse-loop-clause () ; uses loop-*
1160 (let ((word (pop cl--loop-args))
1161 (hash-types '(hash-key hash-keys hash-value hash-values))
1162 (key-types '(key-code key-codes key-seq key-seqs
1163 key-binding key-bindings)))
1164 (cond
1166 ((null cl--loop-args)
1167 (error "Malformed `cl-loop' macro"))
1169 ((eq word 'named)
1170 (setq cl--loop-name (pop cl--loop-args)))
1172 ((eq word 'initially)
1173 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
1174 (or (consp (car cl--loop-args))
1175 (error "Syntax error on `initially' clause"))
1176 (while (consp (car cl--loop-args))
1177 (push (pop cl--loop-args) cl--loop-initially)))
1179 ((eq word 'finally)
1180 (if (eq (car cl--loop-args) 'return)
1181 (setq cl--loop-result-explicit
1182 (or (cl--pop2 cl--loop-args) '(quote nil)))
1183 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
1184 (or (consp (car cl--loop-args))
1185 (error "Syntax error on `finally' clause"))
1186 (if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
1187 (setq cl--loop-result-explicit
1188 (or (nth 1 (pop cl--loop-args)) '(quote nil)))
1189 (while (consp (car cl--loop-args))
1190 (push (pop cl--loop-args) cl--loop-finally)))))
1192 ((memq word '(for as))
1193 (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
1194 (ands nil))
1195 (while
1196 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1197 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
1198 ;; these vars get added to the macro-environment.
1199 (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
1200 (setq word (pop cl--loop-args))
1201 (if (eq word 'being) (setq word (pop cl--loop-args)))
1202 (if (memq word '(the each)) (setq word (pop cl--loop-args)))
1203 (if (memq word '(buffer buffers))
1204 (setq word 'in
1205 cl--loop-args (cons '(buffer-list) cl--loop-args)))
1206 (cond
1208 ((memq word '(from downfrom upfrom to downto upto
1209 above below by))
1210 (push word cl--loop-args)
1211 (if (memq (car cl--loop-args) '(downto above))
1212 (error "Must specify `from' value for downward cl-loop"))
1213 (let* ((down (or (eq (car cl--loop-args) 'downfrom)
1214 (memq (nth 2 cl--loop-args)
1215 '(downto above))))
1216 (excl (or (memq (car cl--loop-args) '(above below))
1217 (memq (nth 2 cl--loop-args)
1218 '(above below))))
1219 (start (and (memq (car cl--loop-args)
1220 '(from upfrom downfrom))
1221 (cl--pop2 cl--loop-args)))
1222 (end (and (memq (car cl--loop-args)
1223 '(to upto downto above below))
1224 (cl--pop2 cl--loop-args)))
1225 (step (and (eq (car cl--loop-args) 'by)
1226 (cl--pop2 cl--loop-args)))
1227 (end-var (and (not (macroexp-const-p end))
1228 (make-symbol "--cl-var--")))
1229 (step-var (and (not (macroexp-const-p step))
1230 (make-symbol "--cl-var--"))))
1231 (and step (numberp step) (<= step 0)
1232 (error "Loop `by' value is not positive: %s" step))
1233 (push (list var (or start 0)) loop-for-bindings)
1234 (if end-var (push (list end-var end) loop-for-bindings))
1235 (if step-var (push (list step-var step)
1236 loop-for-bindings))
1237 (if end
1238 (push (list
1239 (if down (if excl '> '>=) (if excl '< '<=))
1240 var (or end-var end))
1241 cl--loop-body))
1242 (push (list var (list (if down '- '+) var
1243 (or step-var step 1)))
1244 loop-for-steps)))
1246 ((memq word '(in in-ref on))
1247 (let* ((on (eq word 'on))
1248 (temp (if (and on (symbolp var))
1249 var (make-symbol "--cl-var--"))))
1250 (push (list temp (pop cl--loop-args)) loop-for-bindings)
1251 (push `(consp ,temp) cl--loop-body)
1252 (if (eq word 'in-ref)
1253 (push (list var `(car ,temp)) cl--loop-symbol-macs)
1254 (or (eq temp var)
1255 (progn
1256 (push (list var nil) loop-for-bindings)
1257 (push (list var (if on temp `(car ,temp)))
1258 loop-for-sets))))
1259 (push (list temp
1260 (if (eq (car cl--loop-args) 'by)
1261 (let ((step (cl--pop2 cl--loop-args)))
1262 (if (and (memq (car-safe step)
1263 '(quote function
1264 cl-function))
1265 (symbolp (nth 1 step)))
1266 (list (nth 1 step) temp)
1267 `(funcall ,step ,temp)))
1268 `(cdr ,temp)))
1269 loop-for-steps)))
1271 ((eq word '=)
1272 (let* ((start (pop cl--loop-args))
1273 (then (if (eq (car cl--loop-args) 'then)
1274 (cl--pop2 cl--loop-args) start)))
1275 (push (list var nil) loop-for-bindings)
1276 (if (or ands (eq (car cl--loop-args) 'and))
1277 (progn
1278 (push `(,var
1279 (if ,(or cl--loop-first-flag
1280 (setq cl--loop-first-flag
1281 (make-symbol "--cl-var--")))
1282 ,start ,var))
1283 loop-for-sets)
1284 (push (list var then) loop-for-steps))
1285 (push (list var
1286 (if (eq start then) start
1287 `(if ,(or cl--loop-first-flag
1288 (setq cl--loop-first-flag
1289 (make-symbol "--cl-var--")))
1290 ,start ,then)))
1291 loop-for-sets))))
1293 ((memq word '(across across-ref))
1294 (let ((temp-vec (make-symbol "--cl-vec--"))
1295 (temp-idx (make-symbol "--cl-idx--")))
1296 (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
1297 (push (list temp-idx -1) loop-for-bindings)
1298 (push `(< (setq ,temp-idx (1+ ,temp-idx))
1299 (length ,temp-vec))
1300 cl--loop-body)
1301 (if (eq word 'across-ref)
1302 (push (list var `(aref ,temp-vec ,temp-idx))
1303 cl--loop-symbol-macs)
1304 (push (list var nil) loop-for-bindings)
1305 (push (list var `(aref ,temp-vec ,temp-idx))
1306 loop-for-sets))))
1308 ((memq word '(element elements))
1309 (let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
1310 (and (not (memq (car cl--loop-args) '(in of)))
1311 (error "Expected `of'"))))
1312 (seq (cl--pop2 cl--loop-args))
1313 (temp-seq (make-symbol "--cl-seq--"))
1314 (temp-idx
1315 (if (eq (car cl--loop-args) 'using)
1316 (if (and (= (length (cadr cl--loop-args)) 2)
1317 (eq (cl-caadr cl--loop-args) 'index))
1318 (cadr (cl--pop2 cl--loop-args))
1319 (error "Bad `using' clause"))
1320 (make-symbol "--cl-idx--"))))
1321 (push (list temp-seq seq) loop-for-bindings)
1322 (push (list temp-idx 0) loop-for-bindings)
1323 (if ref
1324 (let ((temp-len (make-symbol "--cl-len--")))
1325 (push (list temp-len `(length ,temp-seq))
1326 loop-for-bindings)
1327 (push (list var `(elt ,temp-seq ,temp-idx))
1328 cl--loop-symbol-macs)
1329 (push `(< ,temp-idx ,temp-len) cl--loop-body))
1330 (push (list var nil) loop-for-bindings)
1331 (push `(and ,temp-seq
1332 (or (consp ,temp-seq)
1333 (< ,temp-idx (length ,temp-seq))))
1334 cl--loop-body)
1335 (push (list var `(if (consp ,temp-seq)
1336 (pop ,temp-seq)
1337 (aref ,temp-seq ,temp-idx)))
1338 loop-for-sets))
1339 (push (list temp-idx `(1+ ,temp-idx))
1340 loop-for-steps)))
1342 ((memq word hash-types)
1343 (or (memq (car cl--loop-args) '(in of))
1344 (error "Expected `of'"))
1345 (let* ((table (cl--pop2 cl--loop-args))
1346 (other
1347 (if (eq (car cl--loop-args) 'using)
1348 (if (and (= (length (cadr cl--loop-args)) 2)
1349 (memq (cl-caadr cl--loop-args) hash-types)
1350 (not (eq (cl-caadr cl--loop-args) word)))
1351 (cadr (cl--pop2 cl--loop-args))
1352 (error "Bad `using' clause"))
1353 (make-symbol "--cl-var--"))))
1354 (if (memq word '(hash-value hash-values))
1355 (setq var (prog1 other (setq other var))))
1356 (cl--loop-set-iterator-function
1357 'hash-tables (lambda (body)
1358 `(maphash (lambda (,var ,other) . ,body)
1359 ,table)))))
1361 ((memq word '(symbol present-symbol external-symbol
1362 symbols present-symbols external-symbols))
1363 (let ((ob (and (memq (car cl--loop-args) '(in of))
1364 (cl--pop2 cl--loop-args))))
1365 (cl--loop-set-iterator-function
1366 'symbols (lambda (body)
1367 `(mapatoms (lambda (,var) . ,body) ,ob)))))
1369 ((memq word '(overlay overlays extent extents))
1370 (let ((buf nil) (from nil) (to nil))
1371 (while (memq (car cl--loop-args) '(in of from to))
1372 (cond ((eq (car cl--loop-args) 'from)
1373 (setq from (cl--pop2 cl--loop-args)))
1374 ((eq (car cl--loop-args) 'to)
1375 (setq to (cl--pop2 cl--loop-args)))
1376 (t (setq buf (cl--pop2 cl--loop-args)))))
1377 (cl--loop-set-iterator-function
1378 'overlays (lambda (body)
1379 `(cl--map-overlays
1380 (lambda (,var ,(make-symbol "--cl-var--"))
1381 (progn . ,body) nil)
1382 ,buf ,from ,to)))))
1384 ((memq word '(interval intervals))
1385 (let ((buf nil) (prop nil) (from nil) (to nil)
1386 (var1 (make-symbol "--cl-var1--"))
1387 (var2 (make-symbol "--cl-var2--")))
1388 (while (memq (car cl--loop-args) '(in of property from to))
1389 (cond ((eq (car cl--loop-args) 'from)
1390 (setq from (cl--pop2 cl--loop-args)))
1391 ((eq (car cl--loop-args) 'to)
1392 (setq to (cl--pop2 cl--loop-args)))
1393 ((eq (car cl--loop-args) 'property)
1394 (setq prop (cl--pop2 cl--loop-args)))
1395 (t (setq buf (cl--pop2 cl--loop-args)))))
1396 (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
1397 (setq var1 (car var) var2 (cdr var))
1398 (push (list var `(cons ,var1 ,var2)) loop-for-sets))
1399 (cl--loop-set-iterator-function
1400 'intervals (lambda (body)
1401 `(cl--map-intervals
1402 (lambda (,var1 ,var2) . ,body)
1403 ,buf ,prop ,from ,to)))))
1405 ((memq word key-types)
1406 (or (memq (car cl--loop-args) '(in of))
1407 (error "Expected `of'"))
1408 (let ((cl-map (cl--pop2 cl--loop-args))
1409 (other
1410 (if (eq (car cl--loop-args) 'using)
1411 (if (and (= (length (cadr cl--loop-args)) 2)
1412 (memq (cl-caadr cl--loop-args) key-types)
1413 (not (eq (cl-caadr cl--loop-args) word)))
1414 (cadr (cl--pop2 cl--loop-args))
1415 (error "Bad `using' clause"))
1416 (make-symbol "--cl-var--"))))
1417 (if (memq word '(key-binding key-bindings))
1418 (setq var (prog1 other (setq other var))))
1419 (cl--loop-set-iterator-function
1420 'keys (lambda (body)
1421 `(,(if (memq word '(key-seq key-seqs))
1422 'cl--map-keymap-recursively 'map-keymap)
1423 (lambda (,var ,other) . ,body) ,cl-map)))))
1425 ((memq word '(frame frames screen screens))
1426 (let ((temp (make-symbol "--cl-var--")))
1427 (push (list var '(selected-frame))
1428 loop-for-bindings)
1429 (push (list temp nil) loop-for-bindings)
1430 (push `(prog1 (not (eq ,var ,temp))
1431 (or ,temp (setq ,temp ,var)))
1432 cl--loop-body)
1433 (push (list var `(next-frame ,var))
1434 loop-for-steps)))
1436 ((memq word '(window windows))
1437 (let ((scr (and (memq (car cl--loop-args) '(in of))
1438 (cl--pop2 cl--loop-args)))
1439 (temp (make-symbol "--cl-var--"))
1440 (minip (make-symbol "--cl-minip--")))
1441 (push (list var (if scr
1442 `(frame-selected-window ,scr)
1443 '(selected-window)))
1444 loop-for-bindings)
1445 ;; If we started in the minibuffer, we need to
1446 ;; ensure that next-window will bring us back there
1447 ;; at some point. (Bug#7492).
1448 ;; (Consider using walk-windows instead of cl-loop if
1449 ;; you care about such things.)
1450 (push (list minip `(minibufferp (window-buffer ,var)))
1451 loop-for-bindings)
1452 (push (list temp nil) loop-for-bindings)
1453 (push `(prog1 (not (eq ,var ,temp))
1454 (or ,temp (setq ,temp ,var)))
1455 cl--loop-body)
1456 (push (list var `(next-window ,var ,minip))
1457 loop-for-steps)))
1460 ;; This is an advertised interface: (info "(cl)Other Clauses").
1461 (let ((handler (and (symbolp word)
1462 (get word 'cl-loop-for-handler))))
1463 (if handler
1464 (funcall handler var)
1465 (error "Expected a `for' preposition, found %s" word)))))
1466 (eq (car cl--loop-args) 'and))
1467 (setq ands t)
1468 (pop cl--loop-args))
1469 (if (and ands loop-for-bindings)
1470 (push (nreverse loop-for-bindings) cl--loop-bindings)
1471 (setq cl--loop-bindings (nconc (mapcar 'list loop-for-bindings)
1472 cl--loop-bindings)))
1473 (if loop-for-sets
1474 (push `(progn
1475 ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
1477 cl--loop-body))
1478 (if loop-for-steps
1479 (push (cons (if ands 'cl-psetq 'setq)
1480 (apply 'append (nreverse loop-for-steps)))
1481 cl--loop-steps))))
1483 ((eq word 'repeat)
1484 (let ((temp (make-symbol "--cl-var--")))
1485 (push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
1486 (push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
1488 ((memq word '(collect collecting))
1489 (let ((what (pop cl--loop-args))
1490 (var (cl--loop-handle-accum nil 'nreverse)))
1491 (if (eq var cl--loop-accum-var)
1492 (push `(progn (push ,what ,var) t) cl--loop-body)
1493 (push `(progn
1494 (setq ,var (nconc ,var (list ,what)))
1496 cl--loop-body))))
1498 ((memq word '(nconc nconcing append appending))
1499 (let ((what (pop cl--loop-args))
1500 (var (cl--loop-handle-accum nil 'nreverse)))
1501 (push `(progn
1502 (setq ,var
1503 ,(if (eq var cl--loop-accum-var)
1504 `(nconc
1505 (,(if (memq word '(nconc nconcing))
1506 #'nreverse #'reverse)
1507 ,what)
1508 ,var)
1509 `(,(if (memq word '(nconc nconcing))
1510 #'nconc #'append)
1511 ,var ,what)))
1513 cl--loop-body)))
1515 ((memq word '(concat concating))
1516 (let ((what (pop cl--loop-args))
1517 (var (cl--loop-handle-accum "")))
1518 (push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
1520 ((memq word '(vconcat vconcating))
1521 (let ((what (pop cl--loop-args))
1522 (var (cl--loop-handle-accum [])))
1523 (push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
1525 ((memq word '(sum summing))
1526 (let ((what (pop cl--loop-args))
1527 (var (cl--loop-handle-accum 0)))
1528 (push `(progn (cl-incf ,var ,what) t) cl--loop-body)))
1530 ((memq word '(count counting))
1531 (let ((what (pop cl--loop-args))
1532 (var (cl--loop-handle-accum 0)))
1533 (push `(progn (if ,what (cl-incf ,var)) t) cl--loop-body)))
1535 ((memq word '(minimize minimizing maximize maximizing))
1536 (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
1537 (pop cl--loop-args)
1538 (let* ((var (cl--loop-handle-accum nil))
1539 (func (intern (substring (symbol-name word)
1540 0 3))))
1541 `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
1543 cl--loop-body))
1545 ((eq word 'with)
1546 (let ((bindings nil))
1547 (while (progn (push (list (pop cl--loop-args)
1548 (and (eq (car cl--loop-args) '=)
1549 (cl--pop2 cl--loop-args)))
1550 bindings)
1551 (eq (car cl--loop-args) 'and))
1552 (pop cl--loop-args))
1553 (push (nreverse bindings) cl--loop-bindings)))
1555 ((eq word 'while)
1556 (push (pop cl--loop-args) cl--loop-body))
1558 ((eq word 'until)
1559 (push `(not ,(pop cl--loop-args)) cl--loop-body))
1561 ((eq word 'always)
1562 (or cl--loop-finish-flag
1563 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1564 (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
1565 (setq cl--loop-result t))
1567 ((eq word 'never)
1568 (or cl--loop-finish-flag
1569 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1570 (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
1571 cl--loop-body)
1572 (setq cl--loop-result t))
1574 ((eq word 'thereis)
1575 (or cl--loop-finish-flag
1576 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1577 (or cl--loop-result-var
1578 (setq cl--loop-result-var (make-symbol "--cl-var--")))
1579 (push `(setq ,cl--loop-finish-flag
1580 (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
1581 cl--loop-body))
1583 ((memq word '(if when unless))
1584 (let* ((cond (pop cl--loop-args))
1585 (then (let ((cl--loop-body nil))
1586 (cl--parse-loop-clause)
1587 (cl--loop-build-ands (nreverse cl--loop-body))))
1588 (else (let ((cl--loop-body nil))
1589 (if (eq (car cl--loop-args) 'else)
1590 (progn (pop cl--loop-args) (cl--parse-loop-clause)))
1591 (cl--loop-build-ands (nreverse cl--loop-body))))
1592 (simple (and (eq (car then) t) (eq (car else) t))))
1593 (if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
1594 (if (eq word 'unless) (setq then (prog1 else (setq else then))))
1595 (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
1596 (if simple (nth 1 else) (list (nth 2 else))))))
1597 (setq form (if (cl--expr-contains form 'it)
1598 `(let ((it ,cond)) (if it ,@form))
1599 `(if ,cond ,@form)))
1600 (push (if simple `(progn ,form t) form) cl--loop-body))))
1602 ((memq word '(do doing))
1603 (let ((body nil))
1604 (or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
1605 (while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
1606 (push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
1608 ((eq word 'return)
1609 (or cl--loop-finish-flag
1610 (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
1611 (or cl--loop-result-var
1612 (setq cl--loop-result-var (make-symbol "--cl-var--")))
1613 (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
1614 ,cl--loop-finish-flag nil)
1615 cl--loop-body))
1618 ;; This is an advertised interface: (info "(cl)Other Clauses").
1619 (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
1620 (or handler (error "Expected a cl-loop keyword, found %s" word))
1621 (funcall handler))))
1622 (if (eq (car cl--loop-args) 'and)
1623 (progn (pop cl--loop-args) (cl--parse-loop-clause)))))
1625 (defun cl--unused-var-p (sym)
1626 (or (null sym) (eq ?_ (aref (symbol-name sym) 0))))
1628 (defun cl--loop-let (specs body par) ; modifies cl--loop-bindings
1629 "Build an expression equivalent to (let SPECS BODY).
1630 SPECS can include bindings using `cl-loop's destructuring (not to be
1631 confused with the patterns of `cl-destructuring-bind').
1632 If PAR is nil, do the bindings step by step, like `let*'.
1633 If BODY is `setq', then use SPECS for assignments rather than for bindings."
1634 (let ((temps nil) (new nil))
1635 (when par
1636 (let ((p specs))
1637 (while (and p (or (symbolp (car-safe (car p))) (null (cl-cadar p))))
1638 (setq p (cdr p)))
1639 (when p
1640 (setq par nil)
1641 (dolist (spec specs)
1642 (or (macroexp-const-p (cadr spec))
1643 (let ((temp (make-symbol "--cl-var--")))
1644 (push (list temp (cadr spec)) temps)
1645 (setcar (cdr spec) temp)))))))
1646 (while specs
1647 (let* ((binding (pop specs))
1648 (spec (car-safe binding)))
1649 (if (and (consp binding) (or (consp spec) (cl--unused-var-p spec)))
1650 (let* ((nspecs nil)
1651 (expr (car (cdr-safe binding)))
1652 (temp (last spec 0)))
1653 (if (and (cl--unused-var-p temp) (null expr))
1654 nil ;; Don't bother declaring/setting `temp' since it won't
1655 ;; be used when `expr' is nil, anyway.
1656 (when (or (null temp)
1657 (and (eq body 'setq) (cl--unused-var-p temp)))
1658 ;; Prefer a fresh uninterned symbol over "_to", to avoid
1659 ;; warnings that we set an unused variable.
1660 (setq temp (make-symbol "--cl-var--"))
1661 ;; Make sure this temp variable is locally declared.
1662 (when (eq body 'setq)
1663 (push (list (list temp)) cl--loop-bindings)))
1664 (push (list temp expr) new))
1665 (while (consp spec)
1666 (push (list (pop spec)
1667 (and expr (list (if spec 'pop 'car) temp)))
1668 nspecs))
1669 (setq specs (nconc (nreverse nspecs) specs)))
1670 (push binding new))))
1671 (if (eq body 'setq)
1672 (let ((set (cons (if par 'cl-psetq 'setq)
1673 (apply 'nconc (nreverse new)))))
1674 (if temps `(let* ,(nreverse temps) ,set) set))
1675 `(,(if par 'let 'let*)
1676 ,(nconc (nreverse temps) (nreverse new)) ,@body))))
1678 (defun cl--loop-handle-accum (def &optional func) ; uses loop-*
1679 (if (eq (car cl--loop-args) 'into)
1680 (let ((var (cl--pop2 cl--loop-args)))
1681 (or (memq var cl--loop-accum-vars)
1682 (progn (push (list (list var def)) cl--loop-bindings)
1683 (push var cl--loop-accum-vars)))
1684 var)
1685 (or cl--loop-accum-var
1686 (progn
1687 (push (list (list
1688 (setq cl--loop-accum-var (make-symbol "--cl-var--"))
1689 def))
1690 cl--loop-bindings)
1691 (setq cl--loop-result (if func (list func cl--loop-accum-var)
1692 cl--loop-accum-var))
1693 cl--loop-accum-var))))
1695 (defun cl--loop-build-ands (clauses)
1696 "Return various representations of (and . CLAUSES).
1697 CLAUSES is a list of Elisp expressions, where clauses of the form
1698 \(progn E1 E2 E3 .. t) are the focus of particular optimizations.
1699 The return value has shape (COND BODY COMBO)
1700 such that COMBO is equivalent to (and . CLAUSES)."
1701 (let ((ands nil)
1702 (body nil))
1703 ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
1704 ;; into (progn ,@A ,@B) ,@C.
1705 (while clauses
1706 (if (and (eq (car-safe (car clauses)) 'progn)
1707 (eq (car (last (car clauses))) t))
1708 (if (cdr clauses)
1709 (setq clauses (cons (nconc (butlast (car clauses))
1710 (if (eq (car-safe (cadr clauses))
1711 'progn)
1712 (cl-cdadr clauses)
1713 (list (cadr clauses))))
1714 (cddr clauses)))
1715 ;; A final (progn ,@A t) is moved outside of the `and'.
1716 (setq body (cdr (butlast (pop clauses)))))
1717 (push (pop clauses) ands)))
1718 (setq ands (or (nreverse ands) (list t)))
1719 (list (if (cdr ands) (cons 'and ands) (car ands))
1720 body
1721 (let ((full (if body
1722 (append ands (list (cons 'progn (append body '(t)))))
1723 ands)))
1724 (if (cdr full) (cons 'and full) (car full))))))
1727 ;;; Other iteration control structures.
1729 ;;;###autoload
1730 (defmacro cl-do (steps endtest &rest body)
1731 "The Common Lisp `do' loop.
1733 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1734 (declare (indent 2)
1735 (debug
1736 ((&rest &or symbolp (symbolp &optional form form))
1737 (form body)
1738 cl-declarations body)))
1739 (cl--expand-do-loop steps endtest body nil))
1741 ;;;###autoload
1742 (defmacro cl-do* (steps endtest &rest body)
1743 "The Common Lisp `do*' loop.
1745 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1746 (declare (indent 2) (debug cl-do))
1747 (cl--expand-do-loop steps endtest body t))
1749 (defun cl--expand-do-loop (steps endtest body star)
1750 `(cl-block nil
1751 (,(if star 'let* 'let)
1752 ,(mapcar (lambda (c) (if (consp c) (list (car c) (nth 1 c)) c))
1753 steps)
1754 (while (not ,(car endtest))
1755 ,@body
1756 ,@(let ((sets (mapcar (lambda (c)
1757 (and (consp c) (cdr (cdr c))
1758 (list (car c) (nth 2 c))))
1759 steps)))
1760 (setq sets (delq nil sets))
1761 (and sets
1762 (list (cons (if (or star (not (cdr sets)))
1763 'setq 'cl-psetq)
1764 (apply 'append sets))))))
1765 ,@(or (cdr endtest) '(nil)))))
1767 ;;;###autoload
1768 (defmacro cl-dolist (spec &rest body)
1769 "Loop over a list.
1770 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1771 Then evaluate RESULT to get return value, default nil.
1772 An implicit nil block is established around the loop.
1774 \(fn (VAR LIST [RESULT]) BODY...)"
1775 (declare (debug ((symbolp form &optional form) cl-declarations body))
1776 (indent 1))
1777 (let ((loop `(dolist ,spec ,@body)))
1778 (if (advice-member-p 'cl--wrap-in-nil-block 'dolist)
1779 loop `(cl-block nil ,loop))))
1781 ;;;###autoload
1782 (defmacro cl-dotimes (spec &rest body)
1783 "Loop a certain number of times.
1784 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1785 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1786 nil.
1788 \(fn (VAR COUNT [RESULT]) BODY...)"
1789 (declare (debug cl-dolist) (indent 1))
1790 (let ((loop `(dotimes ,spec ,@body)))
1791 (if (advice-member-p 'cl--wrap-in-nil-block 'dotimes)
1792 loop `(cl-block nil ,loop))))
1794 (defvar cl--tagbody-alist nil)
1796 ;;;###autoload
1797 (defmacro cl-tagbody (&rest labels-or-stmts)
1798 "Execute statements while providing for control transfers to labels.
1799 Each element of LABELS-OR-STMTS can be either a label (integer or symbol)
1800 or a `cons' cell, in which case it's taken to be a statement.
1801 This distinction is made before performing macroexpansion.
1802 Statements are executed in sequence left to right, discarding any return value,
1803 stopping only when reaching the end of LABELS-OR-STMTS.
1804 Any statement can transfer control at any time to the statements that follow
1805 one of the labels with the special form (go LABEL).
1806 Labels have lexical scope and dynamic extent."
1807 (let ((blocks '())
1808 (first-label (if (consp (car labels-or-stmts))
1809 'cl--preamble (pop labels-or-stmts))))
1810 (let ((block (list first-label)))
1811 (dolist (label-or-stmt labels-or-stmts)
1812 (if (consp label-or-stmt) (push label-or-stmt block)
1813 ;; Add a "go to next block" to implement the fallthrough.
1814 (unless (eq 'go (car-safe (car-safe block)))
1815 (push `(go ,label-or-stmt) block))
1816 (push (nreverse block) blocks)
1817 (setq block (list label-or-stmt))))
1818 (unless (eq 'go (car-safe (car-safe block)))
1819 (push `(go cl--exit) block))
1820 (push (nreverse block) blocks))
1821 (let ((catch-tag (make-symbol "cl--tagbody-tag"))
1822 (cl--tagbody-alist cl--tagbody-alist))
1823 (push (cons 'cl--exit catch-tag) cl--tagbody-alist)
1824 (dolist (block blocks)
1825 (push (cons (car block) catch-tag) cl--tagbody-alist))
1826 (macroexpand-all
1827 `(let ((next-label ',first-label))
1828 (while
1829 (not (eq (setq next-label
1830 (catch ',catch-tag
1831 (cl-case next-label
1832 ,@blocks)))
1833 'cl--exit))))
1834 `((go . ,(lambda (label)
1835 (let ((catch-tag (cdr (assq label cl--tagbody-alist))))
1836 (unless catch-tag
1837 (error "Unknown cl-tagbody go label `%S'" label))
1838 `(throw ',catch-tag ',label))))
1839 ,@macroexpand-all-environment)))))
1841 (defun cl--prog (binder bindings body)
1842 (let (decls)
1843 (while (eq 'declare (car-safe (car body)))
1844 (push (pop body) decls))
1845 `(cl-block nil
1846 (,binder ,bindings
1847 ,@(nreverse decls)
1848 (cl-tagbody . ,body)))))
1850 ;;;###autoload
1851 (defmacro cl-prog (bindings &rest body)
1852 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1853 Shorthand for (cl-block nil (let BINDINGS (cl-tagbody BODY)))"
1854 (cl--prog 'let bindings body))
1856 ;;;###autoload
1857 (defmacro cl-prog* (bindings &rest body)
1858 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1859 Shorthand for (cl-block nil (let* BINDINGS (cl-tagbody BODY)))"
1860 (cl--prog 'let* bindings body))
1862 ;;;###autoload
1863 (defmacro cl-do-symbols (spec &rest body)
1864 "Loop over all symbols.
1865 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1866 from OBARRAY.
1868 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1869 (declare (indent 1)
1870 (debug ((symbolp &optional form form) cl-declarations body)))
1871 ;; Apparently this doesn't have an implicit block.
1872 `(cl-block nil
1873 (let (,(car spec))
1874 (mapatoms #'(lambda (,(car spec)) ,@body)
1875 ,@(and (cadr spec) (list (cadr spec))))
1876 ,(nth 2 spec))))
1878 ;;;###autoload
1879 (defmacro cl-do-all-symbols (spec &rest body)
1880 "Like `cl-do-symbols', but use the default obarray.
1882 \(fn (VAR [RESULT]) BODY...)"
1883 (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
1884 `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
1887 ;;; Assignments.
1889 ;;;###autoload
1890 (defmacro cl-psetq (&rest args)
1891 "Set SYMs to the values VALs in parallel.
1892 This is like `setq', except that all VAL forms are evaluated (in order)
1893 before assigning any symbols SYM to the corresponding values.
1895 \(fn SYM VAL SYM VAL ...)"
1896 (declare (debug setq))
1897 (cons 'cl-psetf args))
1900 ;;; Binding control structures.
1902 ;;;###autoload
1903 (defmacro cl-progv (symbols values &rest body)
1904 "Bind SYMBOLS to VALUES dynamically in BODY.
1905 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1906 Each symbol in the first list is bound to the corresponding value in the
1907 second list (or to nil if VALUES is shorter than SYMBOLS); then the
1908 BODY forms are executed and their result is returned. This is much like
1909 a `let' form, except that the list of symbols can be computed at run-time."
1910 (declare (indent 2) (debug (form form body)))
1911 (let ((bodyfun (make-symbol "body"))
1912 (binds (make-symbol "binds"))
1913 (syms (make-symbol "syms"))
1914 (vals (make-symbol "vals")))
1915 `(progn
1916 (let* ((,syms ,symbols)
1917 (,vals ,values)
1918 (,bodyfun (lambda () ,@body))
1919 (,binds ()))
1920 (while ,syms
1921 (push (list (pop ,syms) (list 'quote (pop ,vals))) ,binds))
1922 (eval (list 'let ,binds (list 'funcall (list 'quote ,bodyfun))))))))
1924 (defconst cl--labels-magic (make-symbol "cl--labels-magic"))
1926 (defvar cl--labels-convert-cache nil)
1928 (defun cl--labels-convert (f)
1929 "Special macro-expander to rename (function F) references in `cl-labels'."
1930 (cond
1931 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1932 ;; *after* handling `function', but we want to stop macroexpansion from
1933 ;; being applied infinitely, so we use a cache to return the exact `form'
1934 ;; being expanded even though we don't receive it.
1935 ((eq f (car cl--labels-convert-cache)) (cdr cl--labels-convert-cache))
1937 (let* ((found (assq f macroexpand-all-environment))
1938 (replacement (and found
1939 (ignore-errors
1940 (funcall (cdr found) cl--labels-magic)))))
1941 (if (and replacement (eq cl--labels-magic (car replacement)))
1942 (nth 1 replacement)
1943 (let ((res `(function ,f)))
1944 (setq cl--labels-convert-cache (cons f res))
1945 res))))))
1947 ;;;###autoload
1948 (defmacro cl-flet (bindings &rest body)
1949 "Make local function definitions.
1950 Like `cl-labels' but the definitions are not recursive.
1951 Each binding can take the form (FUNC EXP) where
1952 FUNC is the function name, and EXP is an expression that returns the
1953 function value to which it should be bound, or it can take the more common
1954 form \(FUNC ARGLIST BODY...) which is a shorthand
1955 for (FUNC (lambda ARGLIST BODY)).
1957 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1958 (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
1959 (let ((binds ()) (newenv macroexpand-all-environment))
1960 (dolist (binding bindings)
1961 (let ((var (make-symbol (format "--cl-%s--" (car binding))))
1962 (args-and-body (cdr binding)))
1963 (if (and (= (length args-and-body) 1) (symbolp (car args-and-body)))
1964 ;; Optimize (cl-flet ((fun var)) body).
1965 (setq var (car args-and-body))
1966 (push (list var (if (= (length args-and-body) 1)
1967 (car args-and-body)
1968 `(cl-function (lambda . ,args-and-body))))
1969 binds))
1970 (push (cons (car binding)
1971 (lambda (&rest args)
1972 (if (eq (car args) cl--labels-magic)
1973 (list cl--labels-magic var)
1974 `(funcall ,var ,@args))))
1975 newenv)))
1976 ;; FIXME: Eliminate those functions which aren't referenced.
1977 (macroexp-let* (nreverse binds)
1978 (macroexpand-all
1979 `(progn ,@body)
1980 ;; Don't override lexical-let's macro-expander.
1981 (if (assq 'function newenv) newenv
1982 (cons (cons 'function #'cl--labels-convert) newenv))))))
1984 ;;;###autoload
1985 (defmacro cl-flet* (bindings &rest body)
1986 "Make local function definitions.
1987 Like `cl-flet' but the definitions can refer to previous ones.
1989 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1990 (declare (indent 1) (debug cl-flet))
1991 (cond
1992 ((null bindings) (macroexp-progn body))
1993 ((null (cdr bindings)) `(cl-flet ,bindings ,@body))
1994 (t `(cl-flet (,(pop bindings)) (cl-flet* ,bindings ,@body)))))
1996 ;;;###autoload
1997 (defmacro cl-labels (bindings &rest body)
1998 "Make temporary function bindings.
1999 The bindings can be recursive and the scoping is lexical, but capturing them
2000 in closures will only work if `lexical-binding' is in use.
2002 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
2003 (declare (indent 1) (debug cl-flet))
2004 (let ((binds ()) (newenv macroexpand-all-environment))
2005 (dolist (binding bindings)
2006 (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
2007 (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
2008 (push (cons (car binding)
2009 (lambda (&rest args)
2010 (if (eq (car args) cl--labels-magic)
2011 (list cl--labels-magic var)
2012 (cl-list* 'funcall var args))))
2013 newenv)))
2014 (macroexpand-all `(letrec ,(nreverse binds) ,@body)
2015 ;; Don't override lexical-let's macro-expander.
2016 (if (assq 'function newenv) newenv
2017 (cons (cons 'function #'cl--labels-convert) newenv)))))
2019 ;; The following ought to have a better definition for use with newer
2020 ;; byte compilers.
2021 ;;;###autoload
2022 (defmacro cl-macrolet (bindings &rest body)
2023 "Make temporary macro definitions.
2024 This is like `cl-flet', but for macros instead of functions.
2026 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
2027 (declare (indent 1)
2028 (debug
2029 ((&rest (&define name (&rest arg) cl-declarations-or-string
2030 def-body))
2031 cl-declarations body)))
2032 (if (cdr bindings)
2033 `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
2034 (if (null bindings) (macroexp-progn body)
2035 (let* ((name (caar bindings))
2036 (res (cl--transform-lambda (cdar bindings) name)))
2037 (eval (car res))
2038 (macroexpand-all (macroexp-progn body)
2039 (cons (cons name
2040 (eval `(cl-function (lambda ,@(cdr res))) t))
2041 macroexpand-all-environment))))))
2043 (defconst cl--old-macroexpand
2044 (if (and (boundp 'cl--old-macroexpand)
2045 (eq (symbol-function 'macroexpand)
2046 #'cl--sm-macroexpand))
2047 cl--old-macroexpand
2048 (symbol-function 'macroexpand)))
2050 (defun cl--sm-macroexpand (exp &optional env)
2051 "Special macro expander used inside `cl-symbol-macrolet'.
2052 This function replaces `macroexpand' during macro expansion
2053 of `cl-symbol-macrolet', and does the same thing as `macroexpand'
2054 except that it additionally expands symbol macros."
2055 (let ((macroexpand-all-environment env))
2056 (while
2057 (progn
2058 (setq exp (funcall cl--old-macroexpand exp env))
2059 (pcase exp
2060 ((pred symbolp)
2061 ;; Perform symbol-macro expansion.
2062 (when (cdr (assq (symbol-name exp) env))
2063 (setq exp (cadr (assq (symbol-name exp) env)))))
2064 (`(setq . ,_)
2065 ;; Convert setq to setf if required by symbol-macro expansion.
2066 (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env))
2067 (cdr exp)))
2068 (p args))
2069 (while (and p (symbolp (car p))) (setq p (cddr p)))
2070 (if p (setq exp (cons 'setf args))
2071 (setq exp (cons 'setq args))
2072 ;; Don't loop further.
2073 nil)))
2074 (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2075 ;; CL's symbol-macrolet treats re-bindings as candidates for
2076 ;; expansion (turning the let into a letf if needed), contrary to
2077 ;; Common-Lisp where such re-bindings hide the symbol-macro.
2078 (let ((letf nil) (found nil) (nbs ()))
2079 (dolist (binding bindings)
2080 (let* ((var (if (symbolp binding) binding (car binding)))
2081 (sm (assq (symbol-name var) env)))
2082 (push (if (not (cdr sm))
2083 binding
2084 (let ((nexp (cadr sm)))
2085 (setq found t)
2086 (unless (symbolp nexp) (setq letf t))
2087 (cons nexp (cdr-safe binding))))
2088 nbs)))
2089 (when found
2090 (setq exp `(,(if letf
2091 (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
2092 (car exp))
2093 ,(nreverse nbs)
2094 ,@body)))))
2095 ;; FIXME: The behavior of CL made sense in a dynamically scoped
2096 ;; language, but for lexical scoping, Common-Lisp's behavior might
2097 ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
2098 ;; lexical-let), so maybe we should adjust the behavior based on
2099 ;; the use of lexical-binding.
2100 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2101 ;; (let ((nbs ()) (found nil))
2102 ;; (dolist (binding bindings)
2103 ;; (let* ((var (if (symbolp binding) binding (car binding)))
2104 ;; (name (symbol-name var))
2105 ;; (val (and found (consp binding) (eq 'let* (car exp))
2106 ;; (list (macroexpand-all (cadr binding)
2107 ;; env)))))
2108 ;; (push (if (assq name env)
2109 ;; ;; This binding should hide its symbol-macro,
2110 ;; ;; but given the way macroexpand-all works, we
2111 ;; ;; can't prevent application of `env' to the
2112 ;; ;; sub-expressions, so we need to α-rename this
2113 ;; ;; variable instead.
2114 ;; (let ((nvar (make-symbol
2115 ;; (copy-sequence name))))
2116 ;; (setq found t)
2117 ;; (push (list name nvar) env)
2118 ;; (cons nvar (or val (cdr-safe binding))))
2119 ;; (if val (cons var val) binding))
2120 ;; nbs)))
2121 ;; (when found
2122 ;; (setq exp `(,(car exp)
2123 ;; ,(nreverse nbs)
2124 ;; ,@(macroexp-unprogn
2125 ;; (macroexpand-all (macroexp-progn body)
2126 ;; env)))))
2127 ;; nil))
2129 exp))
2131 ;;;###autoload
2132 (defmacro cl-symbol-macrolet (bindings &rest body)
2133 "Make symbol macro definitions.
2134 Within the body FORMs, references to the variable NAME will be replaced
2135 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
2137 \(fn ((NAME EXPANSION) ...) FORM...)"
2138 (declare (indent 1) (debug ((&rest (symbolp sexp)) cl-declarations body)))
2139 (cond
2140 ((cdr bindings)
2141 `(cl-symbol-macrolet (,(car bindings))
2142 (cl-symbol-macrolet ,(cdr bindings) ,@body)))
2143 ((null bindings) (macroexp-progn body))
2145 (let ((previous-macroexpand (symbol-function 'macroexpand)))
2146 (unwind-protect
2147 (progn
2148 (fset 'macroexpand #'cl--sm-macroexpand)
2149 (let ((expansion
2150 ;; FIXME: For N bindings, this will traverse `body' N times!
2151 (macroexpand-all (macroexp-progn body)
2152 (cons (list (symbol-name (caar bindings))
2153 (cl-cadar bindings))
2154 macroexpand-all-environment))))
2155 (if (or (null (cdar bindings)) (cl-cddar bindings))
2156 (macroexp--warn-and-return
2157 (format-message "Malformed `cl-symbol-macrolet' binding: %S"
2158 (car bindings))
2159 expansion)
2160 expansion)))
2161 (fset 'macroexpand previous-macroexpand))))))
2163 ;;; Multiple values.
2165 ;;;###autoload
2166 (defmacro cl-multiple-value-bind (vars form &rest body)
2167 "Collect multiple return values.
2168 FORM must return a list; the BODY is then executed with the first N elements
2169 of this list bound (`let'-style) to each of the symbols SYM in turn. This
2170 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
2171 simulate true multiple return values. For compatibility, (cl-values A B C) is
2172 a synonym for (list A B C).
2174 \(fn (SYM...) FORM BODY)"
2175 (declare (indent 2) (debug ((&rest symbolp) form body)))
2176 (let ((temp (make-symbol "--cl-var--")) (n -1))
2177 `(let* ((,temp ,form)
2178 ,@(mapcar (lambda (v)
2179 (list v `(nth ,(setq n (1+ n)) ,temp)))
2180 vars))
2181 ,@body)))
2183 ;;;###autoload
2184 (defmacro cl-multiple-value-setq (vars form)
2185 "Collect multiple return values.
2186 FORM must return a list; the first N elements of this list are stored in
2187 each of the symbols SYM in turn. This is analogous to the Common Lisp
2188 `multiple-value-setq' macro, using lists to simulate true multiple return
2189 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
2191 \(fn (SYM...) FORM)"
2192 (declare (indent 1) (debug ((&rest symbolp) form)))
2193 (cond ((null vars) `(progn ,form nil))
2194 ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
2196 (let* ((temp (make-symbol "--cl-var--")) (n 0))
2197 `(let ((,temp ,form))
2198 (prog1 (setq ,(pop vars) (car ,temp))
2199 (setq ,@(apply #'nconc
2200 (mapcar (lambda (v)
2201 (list v `(nth ,(setq n (1+ n))
2202 ,temp)))
2203 vars)))))))))
2206 ;;; Declarations.
2208 ;;;###autoload
2209 (defmacro cl-locally (&rest body)
2210 "Equivalent to `progn'."
2211 (declare (debug t))
2212 (cons 'progn body))
2213 ;;;###autoload
2214 (defmacro cl-the (type form)
2215 "Return FORM. If type-checking is enabled, assert that it is of TYPE."
2216 (declare (indent 1) (debug (cl-type-spec form)))
2217 (if (not (or (not (cl--compiling-file))
2218 (< cl--optimize-speed 3)
2219 (= cl--optimize-safety 3)))
2220 form
2221 (macroexp-let2 macroexp-copyable-p temp form
2222 `(progn (unless (cl-typep ,temp ',type)
2223 (signal 'wrong-type-argument
2224 (list ',type ,temp ',form)))
2225 ,temp))))
2227 (defvar cl--proclaim-history t) ; for future compilers
2228 (defvar cl--declare-stack t) ; for future compilers
2230 (defun cl--do-proclaim (spec hist)
2231 (and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
2232 (cond ((eq (car-safe spec) 'special)
2233 (if (boundp 'byte-compile-bound-variables)
2234 (setq byte-compile-bound-variables
2235 (append (cdr spec) byte-compile-bound-variables))))
2237 ((eq (car-safe spec) 'inline)
2238 (while (setq spec (cdr spec))
2239 (or (memq (get (car spec) 'byte-optimizer)
2240 '(nil byte-compile-inline-expand))
2241 (error "%s already has a byte-optimizer, can't make it inline"
2242 (car spec)))
2243 (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
2245 ((eq (car-safe spec) 'notinline)
2246 (while (setq spec (cdr spec))
2247 (if (eq (get (car spec) 'byte-optimizer)
2248 'byte-compile-inline-expand)
2249 (put (car spec) 'byte-optimizer nil))))
2251 ((eq (car-safe spec) 'optimize)
2252 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
2253 '((0 nil) (1 t) (2 t) (3 t))))
2254 (safety (assq (nth 1 (assq 'safety (cdr spec)))
2255 '((0 t) (1 t) (2 t) (3 nil)))))
2256 (if speed (setq cl--optimize-speed (car speed)
2257 byte-optimize (nth 1 speed)))
2258 (if safety (setq cl--optimize-safety (car safety)
2259 byte-compile-delete-errors (nth 1 safety)))))
2261 ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
2262 (while (setq spec (cdr spec))
2263 (if (consp (car spec))
2264 (if (eq (cl-cadar spec) 0)
2265 (byte-compile-disable-warning (caar spec))
2266 (byte-compile-enable-warning (caar spec)))))))
2267 nil)
2269 ;;; Process any proclamations made before cl-macs was loaded.
2270 (defvar cl--proclaims-deferred)
2271 (let ((p (reverse cl--proclaims-deferred)))
2272 (while p (cl--do-proclaim (pop p) t))
2273 (setq cl--proclaims-deferred nil))
2275 ;;;###autoload
2276 (defmacro cl-declare (&rest specs)
2277 "Declare SPECS about the current function while compiling.
2278 For instance
2280 (cl-declare (warn 0))
2282 will turn off byte-compile warnings in the function.
2283 See Info node `(cl)Declarations' for details."
2284 (if (cl--compiling-file)
2285 (while specs
2286 (if (listp cl--declare-stack) (push (car specs) cl--declare-stack))
2287 (cl--do-proclaim (pop specs) nil)))
2288 nil)
2290 ;;; The standard modify macros.
2292 ;; `setf' is now part of core Elisp, defined in gv.el.
2294 ;;;###autoload
2295 (defmacro cl-psetf (&rest args)
2296 "Set PLACEs to the values VALs in parallel.
2297 This is like `setf', except that all VAL forms are evaluated (in order)
2298 before assigning any PLACEs to the corresponding values.
2300 \(fn PLACE VAL PLACE VAL ...)"
2301 (declare (debug setf))
2302 (let ((p args) (simple t) (vars nil))
2303 (while p
2304 (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
2305 (setq simple nil))
2306 (if (memq (car p) vars)
2307 (error "Destination duplicated in psetf: %s" (car p)))
2308 (push (pop p) vars)
2309 (or p (error "Odd number of arguments to cl-psetf"))
2310 (pop p))
2311 (if simple
2312 `(progn (setq ,@args) nil)
2313 (setq args (reverse args))
2314 (let ((expr `(setf ,(cadr args) ,(car args))))
2315 (while (setq args (cddr args))
2316 (setq expr `(setf ,(cadr args) (prog1 ,(car args) ,expr))))
2317 `(progn ,expr nil)))))
2319 ;;;###autoload
2320 (defmacro cl-remf (place tag)
2321 "Remove TAG from property list PLACE.
2322 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2323 The form returns true if TAG was found and removed, nil otherwise."
2324 (declare (debug (place form)))
2325 (gv-letplace (tval setter) place
2326 (macroexp-let2 macroexp-copyable-p ttag tag
2327 `(if (eq ,ttag (car ,tval))
2328 (progn ,(funcall setter `(cddr ,tval))
2330 (cl--do-remf ,tval ,ttag)))))
2332 ;;;###autoload
2333 (defmacro cl-shiftf (place &rest args)
2334 "Shift left among PLACEs.
2335 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2336 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2338 \(fn PLACE... VAL)"
2339 (declare (debug (&rest place)))
2340 (cond
2341 ((null args) place)
2342 ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
2344 (gv-letplace (getter setter) place
2345 `(prog1 ,getter
2346 ,(funcall setter `(cl-shiftf ,@args)))))))
2348 ;;;###autoload
2349 (defmacro cl-rotatef (&rest args)
2350 "Rotate left among PLACEs.
2351 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2352 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2354 \(fn PLACE...)"
2355 (declare (debug (&rest place)))
2356 (if (not (memq nil (mapcar 'symbolp args)))
2357 (and (cdr args)
2358 (let ((sets nil)
2359 (first (car args)))
2360 (while (cdr args)
2361 (setq sets (nconc sets (list (pop args) (car args)))))
2362 `(cl-psetf ,@sets ,(car args) ,first)))
2363 (let* ((places (reverse args))
2364 (temp (make-symbol "--cl-rotatef--"))
2365 (form temp))
2366 (while (cdr places)
2367 (setq form
2368 (gv-letplace (getter setter) (pop places)
2369 `(prog1 ,getter ,(funcall setter form)))))
2370 (gv-letplace (getter setter) (car places)
2371 (macroexp-let* `((,temp ,getter))
2372 `(progn ,(funcall setter form) nil))))))
2374 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2375 ;; previous state. If the getter/setter loses information, that info is
2376 ;; not recovered.
2378 (defun cl--letf (bindings simplebinds binds body)
2379 ;; It's not quite clear what the semantics of cl-letf should be.
2380 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2381 ;; that the actual assignments ("bindings") should only happen after
2382 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2383 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2384 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2385 ;; or
2386 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2387 ;; or
2388 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2389 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2390 (if (null bindings)
2391 (if (and (null binds) (null simplebinds)) (macroexp-progn body)
2392 `(let* (,@(mapcar (lambda (x)
2393 (pcase-let ((`(,vold ,getter ,_setter ,_vnew) x))
2394 (list vold getter)))
2395 binds)
2396 ,@simplebinds)
2397 (unwind-protect
2398 ,(macroexp-progn
2399 (append
2400 (delq nil
2401 (mapcar (lambda (x)
2402 (pcase x
2403 ;; If there's no vnew, do nothing.
2404 (`(,_vold ,_getter ,setter ,vnew)
2405 (funcall setter vnew))))
2406 binds))
2407 body))
2408 ,@(mapcar (lambda (x)
2409 (pcase-let ((`(,vold ,_getter ,setter ,_vnew) x))
2410 (funcall setter vold)))
2411 binds))))
2412 (let ((binding (car bindings)))
2413 (gv-letplace (getter setter) (car binding)
2414 (macroexp-let2 nil vnew (cadr binding)
2415 (if (symbolp (car binding))
2416 ;; Special-case for simple variables.
2417 (cl--letf (cdr bindings)
2418 (cons `(,getter ,(if (cdr binding) vnew getter))
2419 simplebinds)
2420 binds body)
2421 (cl--letf (cdr bindings) simplebinds
2422 (cons `(,(make-symbol "old") ,getter ,setter
2423 ,@(if (cdr binding) (list vnew)))
2424 binds)
2425 body)))))))
2427 ;;;###autoload
2428 (defmacro cl-letf (bindings &rest body)
2429 "Temporarily bind to PLACEs.
2430 This is the analogue of `let', but with generalized variables (in the
2431 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2432 VALUE, then the BODY forms are executed. On exit, either normally or
2433 because of a `throw' or error, the PLACEs are set back to their original
2434 values. Note that this macro is *not* available in Common Lisp.
2435 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2436 the PLACE is not modified before executing BODY.
2438 \(fn ((PLACE VALUE) ...) BODY...)"
2439 (declare (indent 1) (debug ((&rest (gate gv-place &optional form)) body)))
2440 (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2441 `(let ,bindings ,@body)
2442 (cl--letf bindings () () body)))
2444 ;;;###autoload
2445 (defmacro cl-letf* (bindings &rest body)
2446 "Temporarily bind to PLACEs.
2447 Like `cl-letf' but where the bindings are performed one at a time,
2448 rather than all at the end (i.e. like `let*' rather than like `let')."
2449 (declare (indent 1) (debug cl-letf))
2450 (dolist (binding (reverse bindings))
2451 (setq body (list `(cl-letf (,binding) ,@body))))
2452 (macroexp-progn body))
2454 ;;;###autoload
2455 (defmacro cl-callf (func place &rest args)
2456 "Set PLACE to (FUNC PLACE ARGS...).
2457 FUNC should be an unquoted function name. PLACE may be a symbol,
2458 or any generalized variable allowed by `setf'."
2459 (declare (indent 2) (debug (cl-function place &rest form)))
2460 (gv-letplace (getter setter) place
2461 (let* ((rargs (cons getter args)))
2462 (funcall setter
2463 (if (symbolp func) (cons func rargs)
2464 `(funcall #',func ,@rargs))))))
2466 ;;;###autoload
2467 (defmacro cl-callf2 (func arg1 place &rest args)
2468 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2469 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2471 \(fn FUNC ARG1 PLACE ARGS...)"
2472 (declare (indent 3) (debug (cl-function form place &rest form)))
2473 (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
2474 `(setf ,place (,func ,arg1 ,place ,@args))
2475 (macroexp-let2 nil a1 arg1
2476 (gv-letplace (getter setter) place
2477 (let* ((rargs (cl-list* a1 getter args)))
2478 (funcall setter
2479 (if (symbolp func) (cons func rargs)
2480 `(funcall #',func ,@rargs))))))))
2482 ;;;###autoload
2483 (defmacro cl-defsubst (name args &rest body)
2484 "Define NAME as a function.
2485 Like `defun', except the function is automatically declared `inline' and
2486 the arguments are immutable.
2487 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2488 surrounded by (cl-block NAME ...).
2489 The function's arguments should be treated as immutable.
2491 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2492 (declare (debug cl-defun) (indent 2))
2493 (let* ((argns (cl--arglist-args args))
2494 (real-args (if (eq '&cl-defs (car args)) (cddr args) args))
2495 (p argns)
2496 ;; (pbody (cons 'progn body))
2498 (while (and p (eq (cl--expr-contains real-args (car p)) 1)) (pop p))
2499 `(progn
2500 ,(if p nil ; give up if defaults refer to earlier args
2501 `(cl-define-compiler-macro ,name
2502 ,(if (memq '&key args)
2503 `(&whole cl-whole &cl-quote ,@args)
2504 (cons '&cl-quote args))
2505 (cl--defsubst-expand
2506 ',argns '(cl-block ,name ,@body)
2507 ;; We used to pass `simple' as
2508 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2509 ;; But this is much too simplistic since it
2510 ;; does not pay attention to the argvs (and
2511 ;; cl-expr-access-order itself is also too naive).
2513 ,(and (memq '&key args) 'cl-whole) nil ,@argns)))
2514 (cl-defun ,name ,args ,@body))))
2516 (defun cl--defsubst-expand (argns body simple whole _unsafe &rest argvs)
2517 (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
2518 (if (cl--simple-exprs-p argvs) (setq simple t))
2519 (let* ((substs ())
2520 (lets (delq nil
2521 (cl-mapcar (lambda (argn argv)
2522 (if (or simple (macroexp-const-p argv))
2523 (progn (push (cons argn argv) substs)
2524 nil)
2525 (list argn argv)))
2526 argns argvs))))
2527 ;; FIXME: `sublis/subst' will happily substitute the symbol
2528 ;; `argn' in places where it's not used as a reference
2529 ;; to a variable.
2530 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2531 ;; scope, leading to name capture.
2532 (setq body (cond ((null substs) body)
2533 ((null (cdr substs))
2534 (cl-subst (cdar substs) (caar substs) body))
2535 (t (cl--sublis substs body))))
2536 (if lets `(let ,lets ,body) body))))
2538 (defun cl--sublis (alist tree)
2539 "Perform substitutions indicated by ALIST in TREE (non-destructively)."
2540 (let ((x (assq tree alist)))
2541 (cond
2542 (x (cdr x))
2543 ((consp tree)
2544 (cons (cl--sublis alist (car tree)) (cl--sublis alist (cdr tree))))
2545 (t tree))))
2547 ;;; Structures.
2549 (defmacro cl--find-class (type)
2550 `(get ,type 'cl--class))
2552 ;; Rather than hard code cl-structure-object, we indirect through this variable
2553 ;; for bootstrapping reasons.
2554 (defvar cl--struct-default-parent nil)
2556 ;;;###autoload
2557 (defmacro cl-defstruct (struct &rest descs)
2558 "Define a struct type.
2559 This macro defines a new data type called NAME that stores data
2560 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2561 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2562 You can use the accessors to set the corresponding slots, via `setf'.
2564 NAME may instead take the form (NAME OPTIONS...), where each
2565 OPTION is either a single keyword or (KEYWORD VALUE) where
2566 KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
2567 :type, :named, :initial-offset, :print-function, or :include.
2569 Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
2570 SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
2571 pairs for that slot.
2572 Currently, only one keyword is supported, `:read-only'. If this has a
2573 non-nil value, that slot cannot be set via `setf'.
2575 \(fn NAME SLOTS...)"
2576 (declare (doc-string 2) (indent 1)
2577 (debug
2578 (&define ;Makes top-level form not be wrapped.
2579 [&or symbolp
2580 (gate
2581 symbolp &rest
2582 [&or symbolp
2583 (&or [":conc-name" symbolp]
2584 [":constructor" symbolp &optional cl-lambda-list]
2585 [":copier" symbolp]
2586 [":predicate" symbolp]
2587 [":include" symbolp &rest sexp] ;; Not finished.
2588 [":print-function" sexp]
2589 [":type" symbolp]
2590 [":named"]
2591 [":initial-offset" natnump])])]
2592 [&optional stringp]
2593 ;; All the above is for the following def-form.
2594 &rest &or symbolp (symbolp &optional def-form &rest sexp))))
2595 (let* ((name (if (consp struct) (car struct) struct))
2596 (opts (cdr-safe struct))
2597 (slots nil)
2598 (defaults nil)
2599 (conc-name (concat (symbol-name name) "-"))
2600 (constructor (intern (format "make-%s" name)))
2601 (constrs nil)
2602 (copier (intern (format "copy-%s" name)))
2603 (predicate (intern (format "%s-p" name)))
2604 (print-func nil) (print-auto nil)
2605 (safety (if (cl--compiling-file) cl--optimize-safety 3))
2606 (include nil)
2607 (tag (intern (format "cl-struct-%s" name)))
2608 (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2609 (include-descs nil)
2610 (include-name nil)
2611 (type nil)
2612 (named nil)
2613 (forms nil)
2614 (docstring (if (stringp (car descs)) (pop descs)))
2615 pred-form pred-check)
2616 (setq descs (cons '(cl-tag-slot)
2617 (mapcar (function (lambda (x) (if (consp x) x (list x))))
2618 descs)))
2619 (while opts
2620 (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2621 (args (cdr-safe (pop opts))))
2622 (cond ((eq opt :conc-name)
2623 (if args
2624 (setq conc-name (if (car args)
2625 (symbol-name (car args)) ""))))
2626 ((eq opt :constructor)
2627 (if (cdr args)
2628 (progn
2629 ;; If this defines a constructor of the same name as
2630 ;; the default one, don't define the default.
2631 (if (eq (car args) constructor)
2632 (setq constructor nil))
2633 (push args constrs))
2634 (if args (setq constructor (car args)))))
2635 ((eq opt :copier)
2636 (if args (setq copier (car args))))
2637 ((eq opt :predicate)
2638 (if args (setq predicate (car args))))
2639 ((eq opt :include)
2640 ;; FIXME: Actually, we can include more than once as long as
2641 ;; we include EIEIO classes rather than cl-structs!
2642 (when include-name (error "Can't :include more than once"))
2643 (setq include-name (car args))
2644 (setq include-descs (mapcar (function
2645 (lambda (x)
2646 (if (consp x) x (list x))))
2647 (cdr args))))
2648 ((eq opt :print-function)
2649 (setq print-func (car args)))
2650 ((eq opt :type)
2651 (setq type (car args)))
2652 ((eq opt :named)
2653 (setq named t))
2654 ((eq opt :initial-offset)
2655 (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2656 descs)))
2658 (error "Structure option %s unrecognized" opt)))))
2659 (unless (or include-name type)
2660 (setq include-name cl--struct-default-parent))
2661 (when include-name (setq include (cl--struct-get-class include-name)))
2662 (if print-func
2663 (setq print-func
2664 `(progn (funcall #',print-func cl-x cl-s cl-n) t))
2665 (or type (and include (not (cl--struct-class-print include)))
2666 (setq print-auto t
2667 print-func (and (or (not (or include type)) (null print-func))
2668 `(progn
2669 (princ ,(format "#S(%s" name) cl-s))))))
2670 (if include
2671 (let* ((inc-type (cl--struct-class-type include))
2672 (old-descs (cl-struct-slot-info include)))
2673 (and type (not (eq inc-type type))
2674 (error ":type disagrees with :include for %s" name))
2675 (while include-descs
2676 (setcar (memq (or (assq (caar include-descs) old-descs)
2677 (error "No slot %s in included struct %s"
2678 (caar include-descs) include))
2679 old-descs)
2680 (pop include-descs)))
2681 (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2682 type inc-type
2683 named (if type (assq 'cl-tag-slot descs) 'true))
2684 (if (cl--struct-class-named include) (setq tag name named t)))
2685 (if type
2686 (progn
2687 (or (memq type '(vector list))
2688 (error "Invalid :type specifier: %s" type))
2689 (if named (setq tag name)))
2690 (setq named 'true)))
2691 (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2692 (when (and (null predicate) named)
2693 (setq predicate (intern (format "cl--struct-%s-p" name))))
2694 (setq pred-form (and named
2695 (let ((pos (- (length descs)
2696 (length (memq (assq 'cl-tag-slot descs)
2697 descs)))))
2698 (cond
2699 ((memq type '(nil vector))
2700 `(and (vectorp cl-x)
2701 (>= (length cl-x) ,(length descs))
2702 (memq (aref cl-x ,pos) ,tag-symbol)))
2703 ((= pos 0) `(memq (car-safe cl-x) ,tag-symbol))
2704 (t `(and (consp cl-x)
2705 (memq (nth ,pos cl-x) ,tag-symbol))))))
2706 pred-check (and pred-form (> safety 0)
2707 (if (and (eq (cl-caadr pred-form) 'vectorp)
2708 (= safety 1))
2709 (cons 'and (cl-cdddr pred-form))
2710 `(,predicate cl-x))))
2711 (when pred-form
2712 (push `(cl-defsubst ,predicate (cl-x)
2713 (declare (side-effect-free error-free))
2714 ,(if (eq (car pred-form) 'and)
2715 (append pred-form '(t))
2716 `(and ,pred-form t)))
2717 forms)
2718 (push `(put ',name 'cl-deftype-satisfies ',predicate) forms))
2719 (let ((pos 0) (descp descs))
2720 (while descp
2721 (let* ((desc (pop descp))
2722 (slot (pop desc)))
2723 (if (memq slot '(cl-tag-slot cl-skip-slot))
2724 (progn
2725 (push nil slots)
2726 (push (and (eq slot 'cl-tag-slot) `',tag)
2727 defaults))
2728 (if (assq slot descp)
2729 (error "Duplicate slots named %s in %s" slot name))
2730 (let ((accessor (intern (format "%s%s" conc-name slot))))
2731 (push slot slots)
2732 (push (pop desc) defaults)
2733 ;; The arg "cl-x" is referenced by name in eg pred-form
2734 ;; and pred-check, so changing it is not straightforward.
2735 (push `(cl-defsubst ,accessor (cl-x)
2736 ,(format "Access slot \"%s\" of `%s' struct CL-X."
2737 slot struct)
2738 (declare (side-effect-free t))
2739 ,@(and pred-check
2740 (list `(or ,pred-check
2741 (signal 'wrong-type-argument
2742 (list ',name cl-x)))))
2743 ,(if (memq type '(nil vector)) `(aref cl-x ,pos)
2744 (if (= pos 0) '(car cl-x)
2745 `(nth ,pos cl-x))))
2746 forms)
2747 (when (cl-oddp (length desc))
2748 (push
2749 (macroexp--warn-and-return
2750 (format "Missing value for option `%S' of slot `%s' in struct %s!"
2751 (car (last desc)) slot name)
2752 'nil)
2753 forms)
2754 (when (and (keywordp (car defaults))
2755 (not (keywordp (car desc))))
2756 (let ((kw (car defaults)))
2757 (push
2758 (macroexp--warn-and-return
2759 (format " I'll take `%s' to be an option rather than a default value."
2761 'nil)
2762 forms)
2763 (push kw desc)
2764 (setcar defaults nil))))
2765 (if (plist-get desc ':read-only)
2766 (push `(gv-define-expander ,accessor
2767 (lambda (_cl-do _cl-x)
2768 (error "%s is a read-only slot" ',accessor)))
2769 forms)
2770 ;; For normal slots, we don't need to define a setf-expander,
2771 ;; since gv-get can use the compiler macro to get the
2772 ;; same result.
2773 ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
2774 ;; ;; If cl is loaded only for compilation,
2775 ;; ;; the call to cl--struct-setf-expander would
2776 ;; ;; cause a warning because it may not be
2777 ;; ;; defined at run time. Suppress that warning.
2778 ;; (progn
2779 ;; (declare-function
2780 ;; cl--struct-setf-expander "cl-macs"
2781 ;; (x name accessor pred-form pos))
2782 ;; (cl--struct-setf-expander
2783 ;; cl-val cl-x ',name ',accessor
2784 ;; ,(and pred-check `',pred-check)
2785 ;; ,pos)))
2786 ;; forms)
2788 (if print-auto
2789 (nconc print-func
2790 (list `(princ ,(format " %s" slot) cl-s)
2791 `(prin1 (,accessor cl-x) cl-s)))))))
2792 (setq pos (1+ pos))))
2793 (setq slots (nreverse slots)
2794 defaults (nreverse defaults))
2795 (and copier
2796 (push `(defalias ',copier #'copy-sequence) forms))
2797 (if constructor
2798 (push (list constructor
2799 (cons '&key (delq nil (copy-sequence slots))))
2800 constrs))
2801 (pcase-dolist (`(,cname ,args ,doc) constrs)
2802 (let* ((anames (cl--arglist-args args))
2803 (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
2804 slots defaults)))
2805 (push `(cl-defsubst ,cname
2806 (&cl-defs (nil ,@descs) ,@args)
2807 ,(if (stringp doc) doc
2808 (format "Constructor for objects of type `%s'." name))
2809 ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
2810 '((declare (side-effect-free t))))
2811 (,(or type #'vector) ,@make))
2812 forms)))
2813 (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2814 ;; Don't bother adding to cl-custom-print-functions since it's not used
2815 ;; by anything anyway!
2816 ;;(if print-func
2817 ;; (push `(if (boundp 'cl-custom-print-functions)
2818 ;; (push
2819 ;; ;; The auto-generated function does not pay attention to
2820 ;; ;; the depth argument cl-n.
2821 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2822 ;; (and ,pred-form ,print-func))
2823 ;; cl-custom-print-functions))
2824 ;; forms))
2825 `(progn
2826 (defvar ,tag-symbol)
2827 ,@(nreverse forms)
2828 ;; Call cl-struct-define during compilation as well, so that
2829 ;; a subsequent cl-defstruct in the same file can correctly include this
2830 ;; struct as a parent.
2831 (eval-and-compile
2832 (cl-struct-define ',name ,docstring ',include-name
2833 ',type ,(eq named t) ',descs ',tag-symbol ',tag
2834 ',print-auto))
2835 ',name)))
2837 ;;; Add cl-struct support to pcase
2839 (defun cl--struct-all-parents (class)
2840 (when (cl--struct-class-p class)
2841 (let ((res ())
2842 (classes (list class)))
2843 ;; BFS precedence.
2844 (while (let ((class (pop classes)))
2845 (push class res)
2846 (setq classes
2847 (append classes
2848 (cl--class-parents class)))))
2849 (nreverse res))))
2851 ;;;###autoload
2852 (pcase-defmacro cl-struct (type &rest fields)
2853 "Pcase patterns to match cl-structs.
2854 Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
2855 field NAME is matched against PAT, or they can be of the form NAME which
2856 is a shorthand for (NAME NAME)."
2857 (declare (debug (sexp &rest [&or (sexp pcase-PAT) sexp])))
2858 `(and (pred (pcase--flip cl-typep ',type))
2859 ,@(mapcar
2860 (lambda (field)
2861 (let* ((name (if (consp field) (car field) field))
2862 (pat (if (consp field) (cadr field) field)))
2863 `(app ,(if (eq (cl-struct-sequence-type type) 'list)
2864 `(nth ,(cl-struct-slot-offset type name))
2865 `(pcase--flip aref ,(cl-struct-slot-offset type name)))
2866 ,pat)))
2867 fields)))
2869 (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2)
2870 "Extra special cases for `cl-typep' predicates."
2871 (let* ((x1 pred1) (x2 pred2)
2873 (and (eq 'pcase--flip (car-safe x1)) (setq x1 (cdr x1))
2874 (eq 'cl-typep (car-safe x1)) (setq x1 (cdr x1))
2875 (null (cdr-safe x1)) (setq x1 (car x1))
2876 (eq 'quote (car-safe x1)) (cadr x1)))
2878 (and (eq 'pcase--flip (car-safe x2)) (setq x2 (cdr x2))
2879 (eq 'cl-typep (car-safe x2)) (setq x2 (cdr x2))
2880 (null (cdr-safe x2)) (setq x2 (car x2))
2881 (eq 'quote (car-safe x2)) (cadr x2))))
2883 (and (symbolp t1) (symbolp t2)
2884 (let ((c1 (cl--find-class t1))
2885 (c2 (cl--find-class t2)))
2886 (and c1 c2
2887 (not (or (memq c1 (cl--struct-all-parents c2))
2888 (memq c2 (cl--struct-all-parents c1)))))))
2889 (let ((c1 (and (symbolp t1) (cl--find-class t1))))
2890 (and c1 (cl--struct-class-p c1)
2891 (funcall orig (if (eq 'list (cl-struct-sequence-type t1))
2892 'consp 'vectorp)
2893 pred2)))
2894 (let ((c2 (and (symbolp t2) (cl--find-class t2))))
2895 (and c2 (cl--struct-class-p c2)
2896 (funcall orig pred1
2897 (if (eq 'list (cl-struct-sequence-type t2))
2898 'consp 'vectorp))))
2899 (funcall orig pred1 pred2))))
2900 (advice-add 'pcase--mutually-exclusive-p
2901 :around #'cl--pcase-mutually-exclusive-p)
2904 (defun cl-struct-sequence-type (struct-type)
2905 "Return the sequence used to build STRUCT-TYPE.
2906 STRUCT-TYPE is a symbol naming a struct type. Return `vector' or
2907 `list', or nil if STRUCT-TYPE is not a struct type. "
2908 (declare (side-effect-free t) (pure t))
2909 (cl--struct-class-type (cl--struct-get-class struct-type)))
2911 (defun cl-struct-slot-info (struct-type)
2912 "Return a list of slot names of struct STRUCT-TYPE.
2913 Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
2914 slot name symbol and OPTS is a list of slot options given to
2915 `cl-defstruct'. Dummy slots that represent the struct name and
2916 slots skipped by :initial-offset may appear in the list."
2917 (declare (side-effect-free t) (pure t))
2918 (let* ((class (cl--struct-get-class struct-type))
2919 (slots (cl--struct-class-slots class))
2920 (type (cl--struct-class-type class))
2921 (descs (if type () (list '(cl-tag-slot)))))
2922 (dotimes (i (length slots))
2923 (let ((slot (aref slots i)))
2924 (push `(,(cl--slot-descriptor-name slot)
2925 ,(cl--slot-descriptor-initform slot)
2926 ,@(if (not (eq (cl--slot-descriptor-type slot) t))
2927 `(:type ,(cl--slot-descriptor-type slot)))
2928 ,@(cl--slot-descriptor-props slot))
2929 descs)))
2930 (nreverse descs)))
2932 (define-error 'cl-struct-unknown-slot "struct %S has no slot %S")
2934 (defun cl-struct-slot-offset (struct-type slot-name)
2935 "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
2936 The returned zero-based slot index is relative to the start of
2937 the structure data type and is adjusted for any structure name
2938 and :initial-offset slots. Signal error if struct STRUCT-TYPE
2939 does not contain SLOT-NAME."
2940 (declare (side-effect-free t) (pure t))
2941 (or (gethash slot-name
2942 (cl--class-index-table (cl--struct-get-class struct-type)))
2943 (signal 'cl-struct-unknown-slot (list struct-type slot-name))))
2945 (defvar byte-compile-function-environment)
2946 (defvar byte-compile-macro-environment)
2948 (defun cl--macroexp-fboundp (sym)
2949 "Return non-nil if SYM will be bound when we run the code.
2950 Of course, we really can't know that for sure, so it's just a heuristic."
2951 (or (fboundp sym)
2952 (and (cl--compiling-file)
2953 (or (cdr (assq sym byte-compile-function-environment))
2954 (cdr (assq sym byte-compile-macro-environment))))))
2956 (put 'null 'cl-deftype-satisfies #'null)
2957 (put 'atom 'cl-deftype-satisfies #'atom)
2958 (put 'real 'cl-deftype-satisfies #'numberp)
2959 (put 'fixnum 'cl-deftype-satisfies #'integerp)
2960 (put 'base-char 'cl-deftype-satisfies #'characterp)
2961 (put 'character 'cl-deftype-satisfies #'natnump)
2964 ;;;###autoload
2965 (define-inline cl-typep (val type)
2966 (inline-letevals (val)
2967 (pcase (inline-const-val type)
2968 ((and `(,name . ,args) (guard (get name 'cl-deftype-handler)))
2969 (inline-quote
2970 (cl-typep ,val ',(apply (get name 'cl-deftype-handler) args))))
2971 (`(,(and name (or 'integer 'float 'real 'number))
2972 . ,(or `(,min ,max) pcase--dontcare))
2973 (inline-quote
2974 (and (cl-typep ,val ',name)
2975 ,(if (memq min '(* nil)) t
2976 (if (consp min)
2977 (inline-quote (> ,val ',(car min)))
2978 (inline-quote (>= ,val ',min))))
2979 ,(if (memq max '(* nil)) t
2980 (if (consp max)
2981 (inline-quote (< ,val ',(car max)))
2982 (inline-quote (<= ,val ',max)))))))
2983 (`(not ,type) (inline-quote (not (cl-typep ,val ',type))))
2984 (`(,(and name (or 'and 'or)) . ,types)
2985 (cond
2986 ((null types) (inline-quote ',(eq name 'and)))
2987 ((null (cdr types))
2988 (inline-quote (cl-typep ,val ',(car types))))
2990 (let ((head (car types))
2991 (rest `(,name . ,(cdr types))))
2992 (cond
2993 ((eq name 'and)
2994 (inline-quote (and (cl-typep ,val ',head)
2995 (cl-typep ,val ',rest))))
2997 (inline-quote (or (cl-typep ,val ',head)
2998 (cl-typep ,val ',rest)))))))))
2999 (`(eql ,v) (inline-quote (and (eql ,val ',v) t)))
3000 (`(member . ,args) (inline-quote (and (memql ,val ',args) t)))
3001 (`(satisfies ,pred) (inline-quote (funcall #',pred ,val)))
3002 ((and (pred symbolp) type (guard (get type 'cl-deftype-handler)))
3003 (inline-quote
3004 (cl-typep ,val ',(funcall (get type 'cl-deftype-handler)))))
3005 ((and (pred symbolp) type (guard (get type 'cl-deftype-satisfies)))
3006 (inline-quote (funcall #',(get type 'cl-deftype-satisfies) ,val)))
3007 ((and (or 'nil 't) type) (inline-quote ',type))
3008 ((and (pred symbolp) type)
3009 (let* ((name (symbol-name type))
3010 (namep (intern (concat name "p"))))
3011 (cond
3012 ((cl--macroexp-fboundp namep) (inline-quote (funcall #',namep ,val)))
3013 ((cl--macroexp-fboundp
3014 (setq namep (intern (concat name "-p"))))
3015 (inline-quote (funcall #',namep ,val)))
3016 ((cl--macroexp-fboundp type) (inline-quote (funcall #',type ,val)))
3017 (t (error "Unknown type %S" type)))))
3018 (type (error "Bad type spec: %s" type)))))
3021 ;;;###autoload
3022 (defmacro cl-check-type (form type &optional string)
3023 "Verify that FORM is of type TYPE; signal an error if not.
3024 STRING is an optional description of the desired type."
3025 (declare (debug (place cl-type-spec &optional stringp)))
3026 (and (or (not (cl--compiling-file))
3027 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
3028 (macroexp-let2 macroexp-copyable-p temp form
3029 `(progn (or (cl-typep ,temp ',type)
3030 (signal 'wrong-type-argument
3031 (list ,(or string `',type) ,temp ',form)))
3032 nil))))
3034 ;;;###autoload
3035 (defmacro cl-assert (form &optional show-args string &rest args)
3036 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
3037 "Verify that FORM returns non-nil; signal an error if not.
3038 Second arg SHOW-ARGS means to include arguments of FORM in message.
3039 Other args STRING and ARGS... are arguments to be passed to `error'.
3040 They are not evaluated unless the assertion fails. If STRING is
3041 omitted, a default message listing FORM itself is used."
3042 (declare (debug (form &rest form)))
3043 (and (or (not (cl--compiling-file))
3044 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
3045 (let ((sargs (and show-args
3046 (delq nil (mapcar (lambda (x)
3047 (unless (macroexp-const-p x)
3049 (cdr-safe form))))))
3050 `(progn
3051 (or ,form
3052 (cl--assertion-failed
3053 ',form ,@(if (or string sargs args)
3054 `(,string (list ,@sargs) (list ,@args)))))
3055 nil))))
3057 ;;; Compiler macros.
3059 ;;;###autoload
3060 (defmacro cl-define-compiler-macro (func args &rest body)
3061 "Define a compiler-only macro.
3062 This is like `defmacro', but macro expansion occurs only if the call to
3063 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
3064 for optimizing the way calls to FUNC are compiled; the form returned by
3065 BODY should do the same thing as a call to the normal function called
3066 FUNC, though possibly more efficiently. Note that, like regular macros,
3067 compiler macros are expanded repeatedly until no further expansions are
3068 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
3069 original function call alone by declaring an initial `&whole foo' parameter
3070 and then returning foo."
3071 (declare (debug cl-defmacro) (indent 2))
3072 (let ((p args) (res nil))
3073 (while (consp p) (push (pop p) res))
3074 (setq args (nconc (nreverse res) (and p (list '&rest p)))))
3075 ;; FIXME: The code in bytecomp mishandles top-level expressions that define
3076 ;; uninterned functions. E.g. it would generate code like:
3077 ;; (defalias '#1=#:foo--cmacro #[514 ...])
3078 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
3079 ;; So we circumvent this by using an interned name.
3080 (let ((fname (intern (concat (symbol-name func) "--cmacro"))))
3081 `(eval-and-compile
3082 ;; Name the compiler-macro function, so that `symbol-file' can find it.
3083 (cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
3084 (cons '_cl-whole-arg args))
3085 ,@body)
3086 (put ',func 'compiler-macro #',fname))))
3088 ;;;###autoload
3089 (defun cl-compiler-macroexpand (form)
3090 "Like `macroexpand', but for compiler macros.
3091 Expands FORM repeatedly until no further expansion is possible.
3092 Returns FORM unchanged if it has no compiler macro, or if it has a
3093 macro that returns its `&whole' argument."
3094 (while
3095 (let ((func (car-safe form)) (handler nil))
3096 (while (and (symbolp func)
3097 (not (setq handler (get func 'compiler-macro)))
3098 (fboundp func)
3099 (or (not (autoloadp (symbol-function func)))
3100 (autoload-do-load (symbol-function func) func)))
3101 (setq func (symbol-function func)))
3102 (and handler
3103 (not (eq form (setq form (apply handler form (cdr form))))))))
3104 form)
3106 ;; Optimize away unused block-wrappers.
3108 (defvar cl--active-block-names nil)
3110 (cl-define-compiler-macro cl--block-wrapper (cl-form)
3111 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
3112 (cl--active-block-names (cons cl-entry cl--active-block-names))
3113 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
3114 (macroexp-progn (cddr cl-form))
3115 macroexpand-all-environment)))
3116 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
3117 ;; to indicate that this return value is already fully expanded.
3118 (if (cdr cl-entry)
3119 `(catch ,(nth 1 cl-form) ,@(macroexp-unprogn cl-body))
3120 cl-body)))
3122 (cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
3123 (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
3124 (if cl-found (setcdr cl-found t)))
3125 `(throw ,cl-tag ,cl-value))
3127 ;; Compile-time optimizations for some functions defined in this package.
3129 (defun cl--compiler-macro-member (form a list &rest keys)
3130 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3131 (cl--const-expr-val (nth 1 keys)))))
3132 (cond ((eq test 'eq) `(memq ,a ,list))
3133 ((eq test 'equal) `(member ,a ,list))
3134 ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
3135 (t form))))
3137 (defun cl--compiler-macro-assoc (form a list &rest keys)
3138 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3139 (cl--const-expr-val (nth 1 keys)))))
3140 (cond ((eq test 'eq) `(assq ,a ,list))
3141 ((eq test 'equal) `(assoc ,a ,list))
3142 ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
3143 (if (floatp (cl--const-expr-val a))
3144 `(assoc ,a ,list) `(assq ,a ,list)))
3145 (t form))))
3147 ;;;###autoload
3148 (defun cl--compiler-macro-adjoin (form a list &rest keys)
3149 (if (memq :key keys) form
3150 (macroexp-let2* macroexp-copyable-p ((va a) (vlist list))
3151 `(if (cl-member ,va ,vlist ,@keys) ,vlist (cons ,va ,vlist)))))
3153 (defun cl--compiler-macro-get (_form sym prop &optional def)
3154 (if def
3155 `(cl-getf (symbol-plist ,sym) ,prop ,def)
3156 `(get ,sym ,prop)))
3158 (dolist (y '(cl-first cl-second cl-third cl-fourth
3159 cl-fifth cl-sixth cl-seventh
3160 cl-eighth cl-ninth cl-tenth
3161 cl-rest cl-endp cl-plusp cl-minusp
3162 cl-caaar cl-caadr cl-cadar
3163 cl-caddr cl-cdaar cl-cdadr
3164 cl-cddar cl-cdddr cl-caaaar
3165 cl-caaadr cl-caadar cl-caaddr
3166 cl-cadaar cl-cadadr cl-caddar
3167 cl-cadddr cl-cdaaar cl-cdaadr
3168 cl-cdadar cl-cdaddr cl-cddaar
3169 cl-cddadr cl-cdddar cl-cddddr))
3170 (put y 'side-effect-free t))
3172 ;;; Things that are inline.
3173 (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
3174 cl-notevery cl-revappend cl-nreconc gethash))
3176 ;;; Things that are side-effect-free.
3177 (mapc (lambda (x) (function-put x 'side-effect-free t))
3178 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
3179 cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
3180 cl-subseq cl-list-length cl-get cl-getf))
3182 ;;; Things that are side-effect-and-error-free.
3183 (mapc (lambda (x) (function-put x 'side-effect-free 'error-free))
3184 '(eql cl-list* cl-subst cl-acons cl-equalp
3185 cl-random-state-p copy-tree cl-sublis))
3187 ;;; Types and assertions.
3189 ;;;###autoload
3190 (defmacro cl-deftype (name arglist &rest body)
3191 "Define NAME as a new data type.
3192 The type name can then be used in `cl-typecase', `cl-check-type', etc."
3193 (declare (debug cl-defmacro) (doc-string 3) (indent 2))
3194 `(cl-eval-when (compile load eval)
3195 (put ',name 'cl-deftype-handler
3196 (cl-function (lambda (&cl-defs ('*) ,@arglist) ,@body)))))
3198 (cl-deftype extended-char () `(and character (not base-char)))
3200 ;;; Additional functions that we can now define because we've defined
3201 ;;; `cl-defsubst' and `cl-typep'.
3203 (define-inline cl-struct-slot-value (struct-type slot-name inst)
3204 "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
3205 STRUCT and SLOT-NAME are symbols. INST is a structure instance."
3206 (declare (side-effect-free t))
3207 (inline-letevals (struct-type slot-name inst)
3208 (inline-quote
3209 (progn
3210 (unless (cl-typep ,inst ,struct-type)
3211 (signal 'wrong-type-argument (list ,struct-type ,inst)))
3212 ;; We could use `elt', but since the byte compiler will resolve the
3213 ;; branch below at compile time, it's more efficient to use the
3214 ;; type-specific accessor.
3215 (if (eq (cl-struct-sequence-type ,struct-type) 'list)
3216 (nth (cl-struct-slot-offset ,struct-type ,slot-name) ,inst)
3217 (aref ,inst (cl-struct-slot-offset ,struct-type ,slot-name)))))))
3219 (run-hooks 'cl-macs-load-hook)
3221 ;; Local variables:
3222 ;; byte-compile-dynamic: t
3223 ;; generated-autoload-file: "cl-loaddefs.el"
3224 ;; End:
3226 (provide 'cl-macs)
3228 ;;; cl-macs.el ends here