cl-defstruct: Fix debug spec and check of slot options
[emacs.git] / lisp / emacs-lisp / cl-macs.el
blob0096e0aab3e9c440c414055ebb5a4d675e609cb0
1 ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993, 2001-2016 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 ;; Simple default, which covers 99% of the cases.
927 symbolp form)))
928 (if (not (memq t (mapcar #'symbolp
929 (delq nil (delq t (cl-copy-list loop-args))))))
930 `(cl-block nil (while t ,@loop-args))
931 (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
932 (cl--loop-body nil) (cl--loop-steps nil)
933 (cl--loop-result nil) (cl--loop-result-explicit nil)
934 (cl--loop-result-var nil) (cl--loop-finish-flag nil)
935 (cl--loop-accum-var nil) (cl--loop-accum-vars nil)
936 (cl--loop-initially nil) (cl--loop-finally nil)
937 (cl--loop-iterator-function nil) (cl--loop-first-flag nil)
938 (cl--loop-symbol-macs nil))
939 ;; Here is more or less how those dynbind vars are used after looping
940 ;; over cl--parse-loop-clause:
942 ;; (cl-block ,cl--loop-name
943 ;; (cl-symbol-macrolet ,cl--loop-symbol-macs
944 ;; (foldl #'cl--loop-let
945 ;; `((,cl--loop-result-var)
946 ;; ((,cl--loop-first-flag t))
947 ;; ((,cl--loop-finish-flag t))
948 ;; ,@cl--loop-bindings)
949 ;; ,@(nreverse cl--loop-initially)
950 ;; (while ;(well: cl--loop-iterator-function)
951 ;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
952 ;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
953 ;; ,@(nreverse cl--loop-steps)
954 ;; (setq ,cl--loop-first-flag nil))
955 ;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
956 ;; ,cl--loop-result-var
957 ;; ,@(nreverse cl--loop-finally)
958 ;; ,(or cl--loop-result-explicit
959 ;; cl--loop-result)))))
961 (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
962 (while (not (eq (car cl--loop-args) 'cl-end-loop))
963 (cl--parse-loop-clause))
964 (if cl--loop-finish-flag
965 (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
966 (if cl--loop-first-flag
967 (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
968 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
969 (let* ((epilogue (nconc (nreverse cl--loop-finally)
970 (list (or cl--loop-result-explicit
971 cl--loop-result))))
972 (ands (cl--loop-build-ands (nreverse cl--loop-body)))
973 (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
974 (body (append
975 (nreverse cl--loop-initially)
976 (list (if cl--loop-iterator-function
977 `(cl-block --cl-finish--
978 ,(funcall cl--loop-iterator-function
979 (if (eq (car ands) t) while-body
980 (cons `(or ,(car ands)
981 (cl-return-from
982 --cl-finish--
983 nil))
984 while-body))))
985 `(while ,(car ands) ,@while-body)))
986 (if cl--loop-finish-flag
987 (if (equal epilogue '(nil)) (list cl--loop-result-var)
988 `((if ,cl--loop-finish-flag
989 (progn ,@epilogue) ,cl--loop-result-var)))
990 epilogue))))
991 (if cl--loop-result-var
992 (push (list cl--loop-result-var) cl--loop-bindings))
993 (while cl--loop-bindings
994 (if (cdar cl--loop-bindings)
995 (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
996 (let ((lets nil))
997 (while (and cl--loop-bindings
998 (not (cdar cl--loop-bindings)))
999 (push (car (pop cl--loop-bindings)) lets))
1000 (setq body (list (cl--loop-let lets body nil))))))
1001 (if cl--loop-symbol-macs
1002 (setq body
1003 (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
1004 `(cl-block ,cl--loop-name ,@body)))))
1006 ;; Below is a complete spec for cl-loop, in several parts that correspond
1007 ;; to the syntax given in CLtL2. The specs do more than specify where
1008 ;; the forms are; it also specifies, as much as Edebug allows, all the
1009 ;; syntactically valid cl-loop clauses. The disadvantage of this
1010 ;; completeness is rigidity, but the "for ... being" clause allows
1011 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
1013 ;; (def-edebug-spec cl-loop
1014 ;; ([&optional ["named" symbolp]]
1015 ;; [&rest
1016 ;; &or
1017 ;; ["repeat" form]
1018 ;; loop-for-as
1019 ;; loop-with
1020 ;; loop-initial-final]
1021 ;; [&rest loop-clause]
1022 ;; ))
1024 ;; (def-edebug-spec loop-with
1025 ;; ("with" loop-var
1026 ;; loop-type-spec
1027 ;; [&optional ["=" form]]
1028 ;; &rest ["and" loop-var
1029 ;; loop-type-spec
1030 ;; [&optional ["=" form]]]))
1032 ;; (def-edebug-spec loop-for-as
1033 ;; ([&or "for" "as"] loop-for-as-subclause
1034 ;; &rest ["and" loop-for-as-subclause]))
1036 ;; (def-edebug-spec loop-for-as-subclause
1037 ;; (loop-var
1038 ;; loop-type-spec
1039 ;; &or
1040 ;; [[&or "in" "on" "in-ref" "across-ref"]
1041 ;; form &optional ["by" function-form]]
1043 ;; ["=" form &optional ["then" form]]
1044 ;; ["across" form]
1045 ;; ["being"
1046 ;; [&or "the" "each"]
1047 ;; &or
1048 ;; [[&or "element" "elements"]
1049 ;; [&or "of" "in" "of-ref"] form
1050 ;; &optional "using" ["index" symbolp]];; is this right?
1051 ;; [[&or "hash-key" "hash-keys"
1052 ;; "hash-value" "hash-values"]
1053 ;; [&or "of" "in"]
1054 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
1055 ;; "hash-key" "hash-keys"] sexp)]]
1057 ;; [[&or "symbol" "present-symbol" "external-symbol"
1058 ;; "symbols" "present-symbols" "external-symbols"]
1059 ;; [&or "in" "of"] package-p]
1061 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
1062 ;; [[&or "frame" "frames"
1063 ;; "screen" "screens"
1064 ;; "buffer" "buffers"]]
1066 ;; [[&or "window" "windows"]
1067 ;; [&or "of" "in"] form]
1069 ;; [[&or "overlay" "overlays"
1070 ;; "extent" "extents"]
1071 ;; [&or "of" "in"] form
1072 ;; &optional [[&or "from" "to"] form]]
1074 ;; [[&or "interval" "intervals"]
1075 ;; [&or "in" "of"] form
1076 ;; &optional [[&or "from" "to"] form]
1077 ;; ["property" form]]
1079 ;; [[&or "key-code" "key-codes"
1080 ;; "key-seq" "key-seqs"
1081 ;; "key-binding" "key-bindings"]
1082 ;; [&or "in" "of"] form
1083 ;; &optional ["using" ([&or "key-code" "key-codes"
1084 ;; "key-seq" "key-seqs"
1085 ;; "key-binding" "key-bindings"]
1086 ;; sexp)]]
1087 ;; ;; For arbitrary extensions, recognize anything else.
1088 ;; [symbolp &rest &or symbolp form]
1089 ;; ]
1091 ;; ;; arithmetic - must be last since all parts are optional.
1092 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
1093 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
1094 ;; [&optional ["by" form]]
1095 ;; ]))
1097 ;; (def-edebug-spec loop-initial-final
1098 ;; (&or ["initially"
1099 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
1100 ;; &rest loop-non-atomic-expr]
1101 ;; ["finally" &or
1102 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
1103 ;; ["return" form]]))
1105 ;; (def-edebug-spec loop-and-clause
1106 ;; (loop-clause &rest ["and" loop-clause]))
1108 ;; (def-edebug-spec loop-clause
1109 ;; (&or
1110 ;; [[&or "while" "until" "always" "never" "thereis"] form]
1112 ;; [[&or "collect" "collecting"
1113 ;; "append" "appending"
1114 ;; "nconc" "nconcing"
1115 ;; "concat" "vconcat"] form
1116 ;; [&optional ["into" loop-var]]]
1118 ;; [[&or "count" "counting"
1119 ;; "sum" "summing"
1120 ;; "maximize" "maximizing"
1121 ;; "minimize" "minimizing"] form
1122 ;; [&optional ["into" loop-var]]
1123 ;; loop-type-spec]
1125 ;; [[&or "if" "when" "unless"]
1126 ;; form loop-and-clause
1127 ;; [&optional ["else" loop-and-clause]]
1128 ;; [&optional "end"]]
1130 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
1132 ;; ["return" form]
1133 ;; loop-initial-final
1134 ;; ))
1136 ;; (def-edebug-spec loop-non-atomic-expr
1137 ;; ([&not atom] form))
1139 ;; (def-edebug-spec loop-var
1140 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
1141 ;; ;; loop-var =>
1142 ;; ;; (loop-var . [&or nil loop-var])
1143 ;; ;; (symbolp . [&or nil loop-var])
1144 ;; ;; (symbolp . loop-var)
1145 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
1146 ;; ;; (symbolp . (symbolp . loop-var))
1147 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
1148 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
1150 ;; (def-edebug-spec loop-type-spec
1151 ;; (&optional ["of-type" loop-d-type-spec]))
1153 ;; (def-edebug-spec loop-d-type-spec
1154 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
1158 (defun cl--parse-loop-clause () ; uses loop-*
1159 (let ((word (pop cl--loop-args))
1160 (hash-types '(hash-key hash-keys hash-value hash-values))
1161 (key-types '(key-code key-codes key-seq key-seqs
1162 key-binding key-bindings)))
1163 (cond
1165 ((null cl--loop-args)
1166 (error "Malformed `cl-loop' macro"))
1168 ((eq word 'named)
1169 (setq cl--loop-name (pop cl--loop-args)))
1171 ((eq word 'initially)
1172 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
1173 (or (consp (car cl--loop-args))
1174 (error "Syntax error on `initially' clause"))
1175 (while (consp (car cl--loop-args))
1176 (push (pop cl--loop-args) cl--loop-initially)))
1178 ((eq word 'finally)
1179 (if (eq (car cl--loop-args) 'return)
1180 (setq cl--loop-result-explicit
1181 (or (cl--pop2 cl--loop-args) '(quote nil)))
1182 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
1183 (or (consp (car cl--loop-args))
1184 (error "Syntax error on `finally' clause"))
1185 (if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
1186 (setq cl--loop-result-explicit
1187 (or (nth 1 (pop cl--loop-args)) '(quote nil)))
1188 (while (consp (car cl--loop-args))
1189 (push (pop cl--loop-args) cl--loop-finally)))))
1191 ((memq word '(for as))
1192 (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
1193 (ands nil))
1194 (while
1195 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1196 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
1197 ;; these vars get added to the macro-environment.
1198 (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
1199 (setq word (pop cl--loop-args))
1200 (if (eq word 'being) (setq word (pop cl--loop-args)))
1201 (if (memq word '(the each)) (setq word (pop cl--loop-args)))
1202 (if (memq word '(buffer buffers))
1203 (setq word 'in
1204 cl--loop-args (cons '(buffer-list) cl--loop-args)))
1205 (cond
1207 ((memq word '(from downfrom upfrom to downto upto
1208 above below by))
1209 (push word cl--loop-args)
1210 (if (memq (car cl--loop-args) '(downto above))
1211 (error "Must specify `from' value for downward cl-loop"))
1212 (let* ((down (or (eq (car cl--loop-args) 'downfrom)
1213 (memq (nth 2 cl--loop-args)
1214 '(downto above))))
1215 (excl (or (memq (car cl--loop-args) '(above below))
1216 (memq (nth 2 cl--loop-args)
1217 '(above below))))
1218 (start (and (memq (car cl--loop-args)
1219 '(from upfrom downfrom))
1220 (cl--pop2 cl--loop-args)))
1221 (end (and (memq (car cl--loop-args)
1222 '(to upto downto above below))
1223 (cl--pop2 cl--loop-args)))
1224 (step (and (eq (car cl--loop-args) 'by)
1225 (cl--pop2 cl--loop-args)))
1226 (end-var (and (not (macroexp-const-p end))
1227 (make-symbol "--cl-var--")))
1228 (step-var (and (not (macroexp-const-p step))
1229 (make-symbol "--cl-var--"))))
1230 (and step (numberp step) (<= step 0)
1231 (error "Loop `by' value is not positive: %s" step))
1232 (push (list var (or start 0)) loop-for-bindings)
1233 (if end-var (push (list end-var end) loop-for-bindings))
1234 (if step-var (push (list step-var step)
1235 loop-for-bindings))
1236 (if end
1237 (push (list
1238 (if down (if excl '> '>=) (if excl '< '<=))
1239 var (or end-var end))
1240 cl--loop-body))
1241 (push (list var (list (if down '- '+) var
1242 (or step-var step 1)))
1243 loop-for-steps)))
1245 ((memq word '(in in-ref on))
1246 (let* ((on (eq word 'on))
1247 (temp (if (and on (symbolp var))
1248 var (make-symbol "--cl-var--"))))
1249 (push (list temp (pop cl--loop-args)) loop-for-bindings)
1250 (push `(consp ,temp) cl--loop-body)
1251 (if (eq word 'in-ref)
1252 (push (list var `(car ,temp)) cl--loop-symbol-macs)
1253 (or (eq temp var)
1254 (progn
1255 (push (list var nil) loop-for-bindings)
1256 (push (list var (if on temp `(car ,temp)))
1257 loop-for-sets))))
1258 (push (list temp
1259 (if (eq (car cl--loop-args) 'by)
1260 (let ((step (cl--pop2 cl--loop-args)))
1261 (if (and (memq (car-safe step)
1262 '(quote function
1263 cl-function))
1264 (symbolp (nth 1 step)))
1265 (list (nth 1 step) temp)
1266 `(funcall ,step ,temp)))
1267 `(cdr ,temp)))
1268 loop-for-steps)))
1270 ((eq word '=)
1271 (let* ((start (pop cl--loop-args))
1272 (then (if (eq (car cl--loop-args) 'then)
1273 (cl--pop2 cl--loop-args) start)))
1274 (push (list var nil) loop-for-bindings)
1275 (if (or ands (eq (car cl--loop-args) 'and))
1276 (progn
1277 (push `(,var
1278 (if ,(or cl--loop-first-flag
1279 (setq cl--loop-first-flag
1280 (make-symbol "--cl-var--")))
1281 ,start ,var))
1282 loop-for-sets)
1283 (push (list var then) loop-for-steps))
1284 (push (list var
1285 (if (eq start then) start
1286 `(if ,(or cl--loop-first-flag
1287 (setq cl--loop-first-flag
1288 (make-symbol "--cl-var--")))
1289 ,start ,then)))
1290 loop-for-sets))))
1292 ((memq word '(across across-ref))
1293 (let ((temp-vec (make-symbol "--cl-vec--"))
1294 (temp-idx (make-symbol "--cl-idx--")))
1295 (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
1296 (push (list temp-idx -1) loop-for-bindings)
1297 (push `(< (setq ,temp-idx (1+ ,temp-idx))
1298 (length ,temp-vec))
1299 cl--loop-body)
1300 (if (eq word 'across-ref)
1301 (push (list var `(aref ,temp-vec ,temp-idx))
1302 cl--loop-symbol-macs)
1303 (push (list var nil) loop-for-bindings)
1304 (push (list var `(aref ,temp-vec ,temp-idx))
1305 loop-for-sets))))
1307 ((memq word '(element elements))
1308 (let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
1309 (and (not (memq (car cl--loop-args) '(in of)))
1310 (error "Expected `of'"))))
1311 (seq (cl--pop2 cl--loop-args))
1312 (temp-seq (make-symbol "--cl-seq--"))
1313 (temp-idx
1314 (if (eq (car cl--loop-args) 'using)
1315 (if (and (= (length (cadr cl--loop-args)) 2)
1316 (eq (cl-caadr cl--loop-args) 'index))
1317 (cadr (cl--pop2 cl--loop-args))
1318 (error "Bad `using' clause"))
1319 (make-symbol "--cl-idx--"))))
1320 (push (list temp-seq seq) loop-for-bindings)
1321 (push (list temp-idx 0) loop-for-bindings)
1322 (if ref
1323 (let ((temp-len (make-symbol "--cl-len--")))
1324 (push (list temp-len `(length ,temp-seq))
1325 loop-for-bindings)
1326 (push (list var `(elt ,temp-seq ,temp-idx))
1327 cl--loop-symbol-macs)
1328 (push `(< ,temp-idx ,temp-len) cl--loop-body))
1329 (push (list var nil) loop-for-bindings)
1330 (push `(and ,temp-seq
1331 (or (consp ,temp-seq)
1332 (< ,temp-idx (length ,temp-seq))))
1333 cl--loop-body)
1334 (push (list var `(if (consp ,temp-seq)
1335 (pop ,temp-seq)
1336 (aref ,temp-seq ,temp-idx)))
1337 loop-for-sets))
1338 (push (list temp-idx `(1+ ,temp-idx))
1339 loop-for-steps)))
1341 ((memq word hash-types)
1342 (or (memq (car cl--loop-args) '(in of))
1343 (error "Expected `of'"))
1344 (let* ((table (cl--pop2 cl--loop-args))
1345 (other
1346 (if (eq (car cl--loop-args) 'using)
1347 (if (and (= (length (cadr cl--loop-args)) 2)
1348 (memq (cl-caadr cl--loop-args) hash-types)
1349 (not (eq (cl-caadr cl--loop-args) word)))
1350 (cadr (cl--pop2 cl--loop-args))
1351 (error "Bad `using' clause"))
1352 (make-symbol "--cl-var--"))))
1353 (if (memq word '(hash-value hash-values))
1354 (setq var (prog1 other (setq other var))))
1355 (cl--loop-set-iterator-function
1356 'hash-tables (lambda (body)
1357 `(maphash (lambda (,var ,other) . ,body)
1358 ,table)))))
1360 ((memq word '(symbol present-symbol external-symbol
1361 symbols present-symbols external-symbols))
1362 (let ((ob (and (memq (car cl--loop-args) '(in of))
1363 (cl--pop2 cl--loop-args))))
1364 (cl--loop-set-iterator-function
1365 'symbols (lambda (body)
1366 `(mapatoms (lambda (,var) . ,body) ,ob)))))
1368 ((memq word '(overlay overlays extent extents))
1369 (let ((buf nil) (from nil) (to nil))
1370 (while (memq (car cl--loop-args) '(in of from to))
1371 (cond ((eq (car cl--loop-args) 'from)
1372 (setq from (cl--pop2 cl--loop-args)))
1373 ((eq (car cl--loop-args) 'to)
1374 (setq to (cl--pop2 cl--loop-args)))
1375 (t (setq buf (cl--pop2 cl--loop-args)))))
1376 (cl--loop-set-iterator-function
1377 'overlays (lambda (body)
1378 `(cl--map-overlays
1379 (lambda (,var ,(make-symbol "--cl-var--"))
1380 (progn . ,body) nil)
1381 ,buf ,from ,to)))))
1383 ((memq word '(interval intervals))
1384 (let ((buf nil) (prop nil) (from nil) (to nil)
1385 (var1 (make-symbol "--cl-var1--"))
1386 (var2 (make-symbol "--cl-var2--")))
1387 (while (memq (car cl--loop-args) '(in of property from to))
1388 (cond ((eq (car cl--loop-args) 'from)
1389 (setq from (cl--pop2 cl--loop-args)))
1390 ((eq (car cl--loop-args) 'to)
1391 (setq to (cl--pop2 cl--loop-args)))
1392 ((eq (car cl--loop-args) 'property)
1393 (setq prop (cl--pop2 cl--loop-args)))
1394 (t (setq buf (cl--pop2 cl--loop-args)))))
1395 (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
1396 (setq var1 (car var) var2 (cdr var))
1397 (push (list var `(cons ,var1 ,var2)) loop-for-sets))
1398 (cl--loop-set-iterator-function
1399 'intervals (lambda (body)
1400 `(cl--map-intervals
1401 (lambda (,var1 ,var2) . ,body)
1402 ,buf ,prop ,from ,to)))))
1404 ((memq word key-types)
1405 (or (memq (car cl--loop-args) '(in of))
1406 (error "Expected `of'"))
1407 (let ((cl-map (cl--pop2 cl--loop-args))
1408 (other
1409 (if (eq (car cl--loop-args) 'using)
1410 (if (and (= (length (cadr cl--loop-args)) 2)
1411 (memq (cl-caadr cl--loop-args) key-types)
1412 (not (eq (cl-caadr cl--loop-args) word)))
1413 (cadr (cl--pop2 cl--loop-args))
1414 (error "Bad `using' clause"))
1415 (make-symbol "--cl-var--"))))
1416 (if (memq word '(key-binding key-bindings))
1417 (setq var (prog1 other (setq other var))))
1418 (cl--loop-set-iterator-function
1419 'keys (lambda (body)
1420 `(,(if (memq word '(key-seq key-seqs))
1421 'cl--map-keymap-recursively 'map-keymap)
1422 (lambda (,var ,other) . ,body) ,cl-map)))))
1424 ((memq word '(frame frames screen screens))
1425 (let ((temp (make-symbol "--cl-var--")))
1426 (push (list var '(selected-frame))
1427 loop-for-bindings)
1428 (push (list temp nil) loop-for-bindings)
1429 (push `(prog1 (not (eq ,var ,temp))
1430 (or ,temp (setq ,temp ,var)))
1431 cl--loop-body)
1432 (push (list var `(next-frame ,var))
1433 loop-for-steps)))
1435 ((memq word '(window windows))
1436 (let ((scr (and (memq (car cl--loop-args) '(in of))
1437 (cl--pop2 cl--loop-args)))
1438 (temp (make-symbol "--cl-var--"))
1439 (minip (make-symbol "--cl-minip--")))
1440 (push (list var (if scr
1441 `(frame-selected-window ,scr)
1442 '(selected-window)))
1443 loop-for-bindings)
1444 ;; If we started in the minibuffer, we need to
1445 ;; ensure that next-window will bring us back there
1446 ;; at some point. (Bug#7492).
1447 ;; (Consider using walk-windows instead of cl-loop if
1448 ;; you care about such things.)
1449 (push (list minip `(minibufferp (window-buffer ,var)))
1450 loop-for-bindings)
1451 (push (list temp nil) loop-for-bindings)
1452 (push `(prog1 (not (eq ,var ,temp))
1453 (or ,temp (setq ,temp ,var)))
1454 cl--loop-body)
1455 (push (list var `(next-window ,var ,minip))
1456 loop-for-steps)))
1459 ;; This is an advertised interface: (info "(cl)Other Clauses").
1460 (let ((handler (and (symbolp word)
1461 (get word 'cl-loop-for-handler))))
1462 (if handler
1463 (funcall handler var)
1464 (error "Expected a `for' preposition, found %s" word)))))
1465 (eq (car cl--loop-args) 'and))
1466 (setq ands t)
1467 (pop cl--loop-args))
1468 (if (and ands loop-for-bindings)
1469 (push (nreverse loop-for-bindings) cl--loop-bindings)
1470 (setq cl--loop-bindings (nconc (mapcar 'list loop-for-bindings)
1471 cl--loop-bindings)))
1472 (if loop-for-sets
1473 (push `(progn
1474 ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
1476 cl--loop-body))
1477 (if loop-for-steps
1478 (push (cons (if ands 'cl-psetq 'setq)
1479 (apply 'append (nreverse loop-for-steps)))
1480 cl--loop-steps))))
1482 ((eq word 'repeat)
1483 (let ((temp (make-symbol "--cl-var--")))
1484 (push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
1485 (push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
1487 ((memq word '(collect collecting))
1488 (let ((what (pop cl--loop-args))
1489 (var (cl--loop-handle-accum nil 'nreverse)))
1490 (if (eq var cl--loop-accum-var)
1491 (push `(progn (push ,what ,var) t) cl--loop-body)
1492 (push `(progn
1493 (setq ,var (nconc ,var (list ,what)))
1495 cl--loop-body))))
1497 ((memq word '(nconc nconcing append appending))
1498 (let ((what (pop cl--loop-args))
1499 (var (cl--loop-handle-accum nil 'nreverse)))
1500 (push `(progn
1501 (setq ,var
1502 ,(if (eq var cl--loop-accum-var)
1503 `(nconc
1504 (,(if (memq word '(nconc nconcing))
1505 #'nreverse #'reverse)
1506 ,what)
1507 ,var)
1508 `(,(if (memq word '(nconc nconcing))
1509 #'nconc #'append)
1510 ,var ,what)))
1512 cl--loop-body)))
1514 ((memq word '(concat concating))
1515 (let ((what (pop cl--loop-args))
1516 (var (cl--loop-handle-accum "")))
1517 (push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
1519 ((memq word '(vconcat vconcating))
1520 (let ((what (pop cl--loop-args))
1521 (var (cl--loop-handle-accum [])))
1522 (push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
1524 ((memq word '(sum summing))
1525 (let ((what (pop cl--loop-args))
1526 (var (cl--loop-handle-accum 0)))
1527 (push `(progn (cl-incf ,var ,what) t) cl--loop-body)))
1529 ((memq word '(count counting))
1530 (let ((what (pop cl--loop-args))
1531 (var (cl--loop-handle-accum 0)))
1532 (push `(progn (if ,what (cl-incf ,var)) t) cl--loop-body)))
1534 ((memq word '(minimize minimizing maximize maximizing))
1535 (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
1536 (pop cl--loop-args)
1537 (let* ((var (cl--loop-handle-accum nil))
1538 (func (intern (substring (symbol-name word)
1539 0 3))))
1540 `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
1542 cl--loop-body))
1544 ((eq word 'with)
1545 (let ((bindings nil))
1546 (while (progn (push (list (pop cl--loop-args)
1547 (and (eq (car cl--loop-args) '=)
1548 (cl--pop2 cl--loop-args)))
1549 bindings)
1550 (eq (car cl--loop-args) 'and))
1551 (pop cl--loop-args))
1552 (push (nreverse bindings) cl--loop-bindings)))
1554 ((eq word 'while)
1555 (push (pop cl--loop-args) cl--loop-body))
1557 ((eq word 'until)
1558 (push `(not ,(pop cl--loop-args)) cl--loop-body))
1560 ((eq word 'always)
1561 (or cl--loop-finish-flag
1562 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1563 (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
1564 (setq cl--loop-result t))
1566 ((eq word 'never)
1567 (or cl--loop-finish-flag
1568 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1569 (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
1570 cl--loop-body)
1571 (setq cl--loop-result t))
1573 ((eq word 'thereis)
1574 (or cl--loop-finish-flag
1575 (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1576 (or cl--loop-result-var
1577 (setq cl--loop-result-var (make-symbol "--cl-var--")))
1578 (push `(setq ,cl--loop-finish-flag
1579 (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
1580 cl--loop-body))
1582 ((memq word '(if when unless))
1583 (let* ((cond (pop cl--loop-args))
1584 (then (let ((cl--loop-body nil))
1585 (cl--parse-loop-clause)
1586 (cl--loop-build-ands (nreverse cl--loop-body))))
1587 (else (let ((cl--loop-body nil))
1588 (if (eq (car cl--loop-args) 'else)
1589 (progn (pop cl--loop-args) (cl--parse-loop-clause)))
1590 (cl--loop-build-ands (nreverse cl--loop-body))))
1591 (simple (and (eq (car then) t) (eq (car else) t))))
1592 (if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
1593 (if (eq word 'unless) (setq then (prog1 else (setq else then))))
1594 (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
1595 (if simple (nth 1 else) (list (nth 2 else))))))
1596 (setq form (if (cl--expr-contains form 'it)
1597 `(let ((it ,cond)) (if it ,@form))
1598 `(if ,cond ,@form)))
1599 (push (if simple `(progn ,form t) form) cl--loop-body))))
1601 ((memq word '(do doing))
1602 (let ((body nil))
1603 (or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
1604 (while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
1605 (push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
1607 ((eq word 'return)
1608 (or cl--loop-finish-flag
1609 (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
1610 (or cl--loop-result-var
1611 (setq cl--loop-result-var (make-symbol "--cl-var--")))
1612 (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
1613 ,cl--loop-finish-flag nil)
1614 cl--loop-body))
1617 ;; This is an advertised interface: (info "(cl)Other Clauses").
1618 (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
1619 (or handler (error "Expected a cl-loop keyword, found %s" word))
1620 (funcall handler))))
1621 (if (eq (car cl--loop-args) 'and)
1622 (progn (pop cl--loop-args) (cl--parse-loop-clause)))))
1624 (defun cl--unused-var-p (sym)
1625 (or (null sym) (eq ?_ (aref (symbol-name sym) 0))))
1627 (defun cl--loop-let (specs body par) ; modifies cl--loop-bindings
1628 "Build an expression equivalent to (let SPECS BODY).
1629 SPECS can include bindings using `cl-loop's destructuring (not to be
1630 confused with the patterns of `cl-destructuring-bind').
1631 If PAR is nil, do the bindings step by step, like `let*'.
1632 If BODY is `setq', then use SPECS for assignments rather than for bindings."
1633 (let ((temps nil) (new nil))
1634 (when par
1635 (let ((p specs))
1636 (while (and p (or (symbolp (car-safe (car p))) (null (cl-cadar p))))
1637 (setq p (cdr p)))
1638 (when p
1639 (setq par nil)
1640 (dolist (spec specs)
1641 (or (macroexp-const-p (cadr spec))
1642 (let ((temp (make-symbol "--cl-var--")))
1643 (push (list temp (cadr spec)) temps)
1644 (setcar (cdr spec) temp)))))))
1645 (while specs
1646 (let* ((binding (pop specs))
1647 (spec (car-safe binding)))
1648 (if (and (consp binding) (or (consp spec) (cl--unused-var-p spec)))
1649 (let* ((nspecs nil)
1650 (expr (car (cdr-safe binding)))
1651 (temp (last spec 0)))
1652 (if (and (cl--unused-var-p temp) (null expr))
1653 nil ;; Don't bother declaring/setting `temp' since it won't
1654 ;; be used when `expr' is nil, anyway.
1655 (when (or (null temp)
1656 (and (eq body 'setq) (cl--unused-var-p temp)))
1657 ;; Prefer a fresh uninterned symbol over "_to", to avoid
1658 ;; warnings that we set an unused variable.
1659 (setq temp (make-symbol "--cl-var--"))
1660 ;; Make sure this temp variable is locally declared.
1661 (when (eq body 'setq)
1662 (push (list (list temp)) cl--loop-bindings)))
1663 (push (list temp expr) new))
1664 (while (consp spec)
1665 (push (list (pop spec)
1666 (and expr (list (if spec 'pop 'car) temp)))
1667 nspecs))
1668 (setq specs (nconc (nreverse nspecs) specs)))
1669 (push binding new))))
1670 (if (eq body 'setq)
1671 (let ((set (cons (if par 'cl-psetq 'setq)
1672 (apply 'nconc (nreverse new)))))
1673 (if temps `(let* ,(nreverse temps) ,set) set))
1674 `(,(if par 'let 'let*)
1675 ,(nconc (nreverse temps) (nreverse new)) ,@body))))
1677 (defun cl--loop-handle-accum (def &optional func) ; uses loop-*
1678 (if (eq (car cl--loop-args) 'into)
1679 (let ((var (cl--pop2 cl--loop-args)))
1680 (or (memq var cl--loop-accum-vars)
1681 (progn (push (list (list var def)) cl--loop-bindings)
1682 (push var cl--loop-accum-vars)))
1683 var)
1684 (or cl--loop-accum-var
1685 (progn
1686 (push (list (list
1687 (setq cl--loop-accum-var (make-symbol "--cl-var--"))
1688 def))
1689 cl--loop-bindings)
1690 (setq cl--loop-result (if func (list func cl--loop-accum-var)
1691 cl--loop-accum-var))
1692 cl--loop-accum-var))))
1694 (defun cl--loop-build-ands (clauses)
1695 "Return various representations of (and . CLAUSES).
1696 CLAUSES is a list of Elisp expressions, where clauses of the form
1697 \(progn E1 E2 E3 .. t) are the focus of particular optimizations.
1698 The return value has shape (COND BODY COMBO)
1699 such that COMBO is equivalent to (and . CLAUSES)."
1700 (let ((ands nil)
1701 (body nil))
1702 ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
1703 ;; into (progn ,@A ,@B) ,@C.
1704 (while clauses
1705 (if (and (eq (car-safe (car clauses)) 'progn)
1706 (eq (car (last (car clauses))) t))
1707 (if (cdr clauses)
1708 (setq clauses (cons (nconc (butlast (car clauses))
1709 (if (eq (car-safe (cadr clauses))
1710 'progn)
1711 (cl-cdadr clauses)
1712 (list (cadr clauses))))
1713 (cddr clauses)))
1714 ;; A final (progn ,@A t) is moved outside of the `and'.
1715 (setq body (cdr (butlast (pop clauses)))))
1716 (push (pop clauses) ands)))
1717 (setq ands (or (nreverse ands) (list t)))
1718 (list (if (cdr ands) (cons 'and ands) (car ands))
1719 body
1720 (let ((full (if body
1721 (append ands (list (cons 'progn (append body '(t)))))
1722 ands)))
1723 (if (cdr full) (cons 'and full) (car full))))))
1726 ;;; Other iteration control structures.
1728 ;;;###autoload
1729 (defmacro cl-do (steps endtest &rest body)
1730 "The Common Lisp `do' loop.
1732 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1733 (declare (indent 2)
1734 (debug
1735 ((&rest &or symbolp (symbolp &optional form form))
1736 (form body)
1737 cl-declarations body)))
1738 (cl--expand-do-loop steps endtest body nil))
1740 ;;;###autoload
1741 (defmacro cl-do* (steps endtest &rest body)
1742 "The Common Lisp `do*' loop.
1744 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1745 (declare (indent 2) (debug cl-do))
1746 (cl--expand-do-loop steps endtest body t))
1748 (defun cl--expand-do-loop (steps endtest body star)
1749 `(cl-block nil
1750 (,(if star 'let* 'let)
1751 ,(mapcar (lambda (c) (if (consp c) (list (car c) (nth 1 c)) c))
1752 steps)
1753 (while (not ,(car endtest))
1754 ,@body
1755 ,@(let ((sets (mapcar (lambda (c)
1756 (and (consp c) (cdr (cdr c))
1757 (list (car c) (nth 2 c))))
1758 steps)))
1759 (setq sets (delq nil sets))
1760 (and sets
1761 (list (cons (if (or star (not (cdr sets)))
1762 'setq 'cl-psetq)
1763 (apply 'append sets))))))
1764 ,@(or (cdr endtest) '(nil)))))
1766 ;;;###autoload
1767 (defmacro cl-dolist (spec &rest body)
1768 "Loop over a list.
1769 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1770 Then evaluate RESULT to get return value, default nil.
1771 An implicit nil block is established around the loop.
1773 \(fn (VAR LIST [RESULT]) BODY...)"
1774 (declare (debug ((symbolp form &optional form) cl-declarations body))
1775 (indent 1))
1776 (let ((loop `(dolist ,spec ,@body)))
1777 (if (advice-member-p 'cl--wrap-in-nil-block 'dolist)
1778 loop `(cl-block nil ,loop))))
1780 ;;;###autoload
1781 (defmacro cl-dotimes (spec &rest body)
1782 "Loop a certain number of times.
1783 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1784 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1785 nil.
1787 \(fn (VAR COUNT [RESULT]) BODY...)"
1788 (declare (debug cl-dolist) (indent 1))
1789 (let ((loop `(dotimes ,spec ,@body)))
1790 (if (advice-member-p 'cl--wrap-in-nil-block 'dotimes)
1791 loop `(cl-block nil ,loop))))
1793 (defvar cl--tagbody-alist nil)
1795 ;;;###autoload
1796 (defmacro cl-tagbody (&rest labels-or-stmts)
1797 "Execute statements while providing for control transfers to labels.
1798 Each element of LABELS-OR-STMTS can be either a label (integer or symbol)
1799 or a `cons' cell, in which case it's taken to be a statement.
1800 This distinction is made before performing macroexpansion.
1801 Statements are executed in sequence left to right, discarding any return value,
1802 stopping only when reaching the end of LABELS-OR-STMTS.
1803 Any statement can transfer control at any time to the statements that follow
1804 one of the labels with the special form (go LABEL).
1805 Labels have lexical scope and dynamic extent."
1806 (let ((blocks '())
1807 (first-label (if (consp (car labels-or-stmts))
1808 'cl--preamble (pop labels-or-stmts))))
1809 (let ((block (list first-label)))
1810 (dolist (label-or-stmt labels-or-stmts)
1811 (if (consp label-or-stmt) (push label-or-stmt block)
1812 ;; Add a "go to next block" to implement the fallthrough.
1813 (unless (eq 'go (car-safe (car-safe block)))
1814 (push `(go ,label-or-stmt) block))
1815 (push (nreverse block) blocks)
1816 (setq block (list label-or-stmt))))
1817 (unless (eq 'go (car-safe (car-safe block)))
1818 (push `(go cl--exit) block))
1819 (push (nreverse block) blocks))
1820 (let ((catch-tag (make-symbol "cl--tagbody-tag"))
1821 (cl--tagbody-alist cl--tagbody-alist))
1822 (push (cons 'cl--exit catch-tag) cl--tagbody-alist)
1823 (dolist (block blocks)
1824 (push (cons (car block) catch-tag) cl--tagbody-alist))
1825 (macroexpand-all
1826 `(let ((next-label ',first-label))
1827 (while
1828 (not (eq (setq next-label
1829 (catch ',catch-tag
1830 (cl-case next-label
1831 ,@blocks)))
1832 'cl--exit))))
1833 `((go . ,(lambda (label)
1834 (let ((catch-tag (cdr (assq label cl--tagbody-alist))))
1835 (unless catch-tag
1836 (error "Unknown cl-tagbody go label `%S'" label))
1837 `(throw ',catch-tag ',label))))
1838 ,@macroexpand-all-environment)))))
1840 (defun cl--prog (binder bindings body)
1841 (let (decls)
1842 (while (eq 'declare (car-safe (car body)))
1843 (push (pop body) decls))
1844 `(cl-block nil
1845 (,binder ,bindings
1846 ,@(nreverse decls)
1847 (cl-tagbody . ,body)))))
1849 ;;;###autoload
1850 (defmacro cl-prog (bindings &rest body)
1851 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1852 Shorthand for (cl-block nil (let BINDINGS (cl-tagbody BODY)))"
1853 (cl--prog 'let bindings body))
1855 ;;;###autoload
1856 (defmacro cl-prog* (bindings &rest body)
1857 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1858 Shorthand for (cl-block nil (let* BINDINGS (cl-tagbody BODY)))"
1859 (cl--prog 'let* bindings body))
1861 ;;;###autoload
1862 (defmacro cl-do-symbols (spec &rest body)
1863 "Loop over all symbols.
1864 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1865 from OBARRAY.
1867 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1868 (declare (indent 1)
1869 (debug ((symbolp &optional form form) cl-declarations body)))
1870 ;; Apparently this doesn't have an implicit block.
1871 `(cl-block nil
1872 (let (,(car spec))
1873 (mapatoms #'(lambda (,(car spec)) ,@body)
1874 ,@(and (cadr spec) (list (cadr spec))))
1875 ,(nth 2 spec))))
1877 ;;;###autoload
1878 (defmacro cl-do-all-symbols (spec &rest body)
1879 "Like `cl-do-symbols', but use the default obarray.
1881 \(fn (VAR [RESULT]) BODY...)"
1882 (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
1883 `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
1886 ;;; Assignments.
1888 ;;;###autoload
1889 (defmacro cl-psetq (&rest args)
1890 "Set SYMs to the values VALs in parallel.
1891 This is like `setq', except that all VAL forms are evaluated (in order)
1892 before assigning any symbols SYM to the corresponding values.
1894 \(fn SYM VAL SYM VAL ...)"
1895 (declare (debug setq))
1896 (cons 'cl-psetf args))
1899 ;;; Binding control structures.
1901 ;;;###autoload
1902 (defmacro cl-progv (symbols values &rest body)
1903 "Bind SYMBOLS to VALUES dynamically in BODY.
1904 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1905 Each symbol in the first list is bound to the corresponding value in the
1906 second list (or to nil if VALUES is shorter than SYMBOLS); then the
1907 BODY forms are executed and their result is returned. This is much like
1908 a `let' form, except that the list of symbols can be computed at run-time."
1909 (declare (indent 2) (debug (form form body)))
1910 (let ((bodyfun (make-symbol "body"))
1911 (binds (make-symbol "binds"))
1912 (syms (make-symbol "syms"))
1913 (vals (make-symbol "vals")))
1914 `(progn
1915 (let* ((,syms ,symbols)
1916 (,vals ,values)
1917 (,bodyfun (lambda () ,@body))
1918 (,binds ()))
1919 (while ,syms
1920 (push (list (pop ,syms) (list 'quote (pop ,vals))) ,binds))
1921 (eval (list 'let ,binds (list 'funcall (list 'quote ,bodyfun))))))))
1923 (defconst cl--labels-magic (make-symbol "cl--labels-magic"))
1925 (defvar cl--labels-convert-cache nil)
1927 (defun cl--labels-convert (f)
1928 "Special macro-expander to rename (function F) references in `cl-labels'."
1929 (cond
1930 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1931 ;; *after* handling `function', but we want to stop macroexpansion from
1932 ;; being applied infinitely, so we use a cache to return the exact `form'
1933 ;; being expanded even though we don't receive it.
1934 ((eq f (car cl--labels-convert-cache)) (cdr cl--labels-convert-cache))
1936 (let* ((found (assq f macroexpand-all-environment))
1937 (replacement (and found
1938 (ignore-errors
1939 (funcall (cdr found) cl--labels-magic)))))
1940 (if (and replacement (eq cl--labels-magic (car replacement)))
1941 (nth 1 replacement)
1942 (let ((res `(function ,f)))
1943 (setq cl--labels-convert-cache (cons f res))
1944 res))))))
1946 ;;;###autoload
1947 (defmacro cl-flet (bindings &rest body)
1948 "Make local function definitions.
1949 Like `cl-labels' but the definitions are not recursive.
1950 Each binding can take the form (FUNC EXP) where
1951 FUNC is the function name, and EXP is an expression that returns the
1952 function value to which it should be bound, or it can take the more common
1953 form \(FUNC ARGLIST BODY...) which is a shorthand
1954 for (FUNC (lambda ARGLIST BODY)).
1956 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1957 (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
1958 (let ((binds ()) (newenv macroexpand-all-environment))
1959 (dolist (binding bindings)
1960 (let ((var (make-symbol (format "--cl-%s--" (car binding))))
1961 (args-and-body (cdr binding)))
1962 (if (and (= (length args-and-body) 1) (symbolp (car args-and-body)))
1963 ;; Optimize (cl-flet ((fun var)) body).
1964 (setq var (car args-and-body))
1965 (push (list var (if (= (length args-and-body) 1)
1966 (car args-and-body)
1967 `(cl-function (lambda . ,args-and-body))))
1968 binds))
1969 (push (cons (car binding)
1970 (lambda (&rest args)
1971 (if (eq (car args) cl--labels-magic)
1972 (list cl--labels-magic var)
1973 `(funcall ,var ,@args))))
1974 newenv)))
1975 ;; FIXME: Eliminate those functions which aren't referenced.
1976 (macroexp-let* (nreverse binds)
1977 (macroexpand-all
1978 `(progn ,@body)
1979 ;; Don't override lexical-let's macro-expander.
1980 (if (assq 'function newenv) newenv
1981 (cons (cons 'function #'cl--labels-convert) newenv))))))
1983 ;;;###autoload
1984 (defmacro cl-flet* (bindings &rest body)
1985 "Make local function definitions.
1986 Like `cl-flet' but the definitions can refer to previous ones.
1988 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1989 (declare (indent 1) (debug cl-flet))
1990 (cond
1991 ((null bindings) (macroexp-progn body))
1992 ((null (cdr bindings)) `(cl-flet ,bindings ,@body))
1993 (t `(cl-flet (,(pop bindings)) (cl-flet* ,bindings ,@body)))))
1995 ;;;###autoload
1996 (defmacro cl-labels (bindings &rest body)
1997 "Make temporary function bindings.
1998 The bindings can be recursive and the scoping is lexical, but capturing them
1999 in closures will only work if `lexical-binding' is in use.
2001 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
2002 (declare (indent 1) (debug cl-flet))
2003 (let ((binds ()) (newenv macroexpand-all-environment))
2004 (dolist (binding bindings)
2005 (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
2006 (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
2007 (push (cons (car binding)
2008 (lambda (&rest args)
2009 (if (eq (car args) cl--labels-magic)
2010 (list cl--labels-magic var)
2011 (cl-list* 'funcall var args))))
2012 newenv)))
2013 (macroexpand-all `(letrec ,(nreverse binds) ,@body)
2014 ;; Don't override lexical-let's macro-expander.
2015 (if (assq 'function newenv) newenv
2016 (cons (cons 'function #'cl--labels-convert) newenv)))))
2018 ;; The following ought to have a better definition for use with newer
2019 ;; byte compilers.
2020 ;;;###autoload
2021 (defmacro cl-macrolet (bindings &rest body)
2022 "Make temporary macro definitions.
2023 This is like `cl-flet', but for macros instead of functions.
2025 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
2026 (declare (indent 1)
2027 (debug
2028 ((&rest (&define name (&rest arg) cl-declarations-or-string
2029 def-body))
2030 cl-declarations body)))
2031 (if (cdr bindings)
2032 `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
2033 (if (null bindings) (macroexp-progn body)
2034 (let* ((name (caar bindings))
2035 (res (cl--transform-lambda (cdar bindings) name)))
2036 (eval (car res))
2037 (macroexpand-all (macroexp-progn body)
2038 (cons (cons name
2039 (eval `(cl-function (lambda ,@(cdr res))) t))
2040 macroexpand-all-environment))))))
2042 (defconst cl--old-macroexpand
2043 (if (and (boundp 'cl--old-macroexpand)
2044 (eq (symbol-function 'macroexpand)
2045 #'cl--sm-macroexpand))
2046 cl--old-macroexpand
2047 (symbol-function 'macroexpand)))
2049 (defun cl--sm-macroexpand (exp &optional env)
2050 "Special macro expander used inside `cl-symbol-macrolet'.
2051 This function replaces `macroexpand' during macro expansion
2052 of `cl-symbol-macrolet', and does the same thing as `macroexpand'
2053 except that it additionally expands symbol macros."
2054 (let ((macroexpand-all-environment env))
2055 (while
2056 (progn
2057 (setq exp (funcall cl--old-macroexpand exp env))
2058 (pcase exp
2059 ((pred symbolp)
2060 ;; Perform symbol-macro expansion.
2061 (when (cdr (assq (symbol-name exp) env))
2062 (setq exp (cadr (assq (symbol-name exp) env)))))
2063 (`(setq . ,_)
2064 ;; Convert setq to setf if required by symbol-macro expansion.
2065 (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env))
2066 (cdr exp)))
2067 (p args))
2068 (while (and p (symbolp (car p))) (setq p (cddr p)))
2069 (if p (setq exp (cons 'setf args))
2070 (setq exp (cons 'setq args))
2071 ;; Don't loop further.
2072 nil)))
2073 (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2074 ;; CL's symbol-macrolet treats re-bindings as candidates for
2075 ;; expansion (turning the let into a letf if needed), contrary to
2076 ;; Common-Lisp where such re-bindings hide the symbol-macro.
2077 (let ((letf nil) (found nil) (nbs ()))
2078 (dolist (binding bindings)
2079 (let* ((var (if (symbolp binding) binding (car binding)))
2080 (sm (assq (symbol-name var) env)))
2081 (push (if (not (cdr sm))
2082 binding
2083 (let ((nexp (cadr sm)))
2084 (setq found t)
2085 (unless (symbolp nexp) (setq letf t))
2086 (cons nexp (cdr-safe binding))))
2087 nbs)))
2088 (when found
2089 (setq exp `(,(if letf
2090 (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
2091 (car exp))
2092 ,(nreverse nbs)
2093 ,@body)))))
2094 ;; FIXME: The behavior of CL made sense in a dynamically scoped
2095 ;; language, but for lexical scoping, Common-Lisp's behavior might
2096 ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
2097 ;; lexical-let), so maybe we should adjust the behavior based on
2098 ;; the use of lexical-binding.
2099 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2100 ;; (let ((nbs ()) (found nil))
2101 ;; (dolist (binding bindings)
2102 ;; (let* ((var (if (symbolp binding) binding (car binding)))
2103 ;; (name (symbol-name var))
2104 ;; (val (and found (consp binding) (eq 'let* (car exp))
2105 ;; (list (macroexpand-all (cadr binding)
2106 ;; env)))))
2107 ;; (push (if (assq name env)
2108 ;; ;; This binding should hide its symbol-macro,
2109 ;; ;; but given the way macroexpand-all works, we
2110 ;; ;; can't prevent application of `env' to the
2111 ;; ;; sub-expressions, so we need to α-rename this
2112 ;; ;; variable instead.
2113 ;; (let ((nvar (make-symbol
2114 ;; (copy-sequence name))))
2115 ;; (setq found t)
2116 ;; (push (list name nvar) env)
2117 ;; (cons nvar (or val (cdr-safe binding))))
2118 ;; (if val (cons var val) binding))
2119 ;; nbs)))
2120 ;; (when found
2121 ;; (setq exp `(,(car exp)
2122 ;; ,(nreverse nbs)
2123 ;; ,@(macroexp-unprogn
2124 ;; (macroexpand-all (macroexp-progn body)
2125 ;; env)))))
2126 ;; nil))
2128 exp))
2130 ;;;###autoload
2131 (defmacro cl-symbol-macrolet (bindings &rest body)
2132 "Make symbol macro definitions.
2133 Within the body FORMs, references to the variable NAME will be replaced
2134 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
2136 \(fn ((NAME EXPANSION) ...) FORM...)"
2137 (declare (indent 1) (debug ((&rest (symbol sexp)) cl-declarations body)))
2138 (cond
2139 ((cdr bindings)
2140 `(cl-symbol-macrolet (,(car bindings))
2141 (cl-symbol-macrolet ,(cdr bindings) ,@body)))
2142 ((null bindings) (macroexp-progn body))
2144 (let ((previous-macroexpand (symbol-function 'macroexpand)))
2145 (unwind-protect
2146 (progn
2147 (fset 'macroexpand #'cl--sm-macroexpand)
2148 (let ((expansion
2149 ;; FIXME: For N bindings, this will traverse `body' N times!
2150 (macroexpand-all (macroexp-progn body)
2151 (cons (list (symbol-name (caar bindings))
2152 (cl-cadar bindings))
2153 macroexpand-all-environment))))
2154 (if (or (null (cdar bindings)) (cl-cddar bindings))
2155 (macroexp--warn-and-return
2156 (format-message "Malformed `cl-symbol-macrolet' binding: %S"
2157 (car bindings))
2158 expansion)
2159 expansion)))
2160 (fset 'macroexpand previous-macroexpand))))))
2162 ;;; Multiple values.
2164 ;;;###autoload
2165 (defmacro cl-multiple-value-bind (vars form &rest body)
2166 "Collect multiple return values.
2167 FORM must return a list; the BODY is then executed with the first N elements
2168 of this list bound (`let'-style) to each of the symbols SYM in turn. This
2169 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
2170 simulate true multiple return values. For compatibility, (cl-values A B C) is
2171 a synonym for (list A B C).
2173 \(fn (SYM...) FORM BODY)"
2174 (declare (indent 2) (debug ((&rest symbolp) form body)))
2175 (let ((temp (make-symbol "--cl-var--")) (n -1))
2176 `(let* ((,temp ,form)
2177 ,@(mapcar (lambda (v)
2178 (list v `(nth ,(setq n (1+ n)) ,temp)))
2179 vars))
2180 ,@body)))
2182 ;;;###autoload
2183 (defmacro cl-multiple-value-setq (vars form)
2184 "Collect multiple return values.
2185 FORM must return a list; the first N elements of this list are stored in
2186 each of the symbols SYM in turn. This is analogous to the Common Lisp
2187 `multiple-value-setq' macro, using lists to simulate true multiple return
2188 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
2190 \(fn (SYM...) FORM)"
2191 (declare (indent 1) (debug ((&rest symbolp) form)))
2192 (cond ((null vars) `(progn ,form nil))
2193 ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
2195 (let* ((temp (make-symbol "--cl-var--")) (n 0))
2196 `(let ((,temp ,form))
2197 (prog1 (setq ,(pop vars) (car ,temp))
2198 (setq ,@(apply #'nconc
2199 (mapcar (lambda (v)
2200 (list v `(nth ,(setq n (1+ n))
2201 ,temp)))
2202 vars)))))))))
2205 ;;; Declarations.
2207 ;;;###autoload
2208 (defmacro cl-locally (&rest body)
2209 "Equivalent to `progn'."
2210 (declare (debug t))
2211 (cons 'progn body))
2212 ;;;###autoload
2213 (defmacro cl-the (type form)
2214 "Return FORM. If type-checking is enabled, assert that it is of TYPE."
2215 (declare (indent 1) (debug (cl-type-spec form)))
2216 (if (not (or (not (cl--compiling-file))
2217 (< cl--optimize-speed 3)
2218 (= cl--optimize-safety 3)))
2219 form
2220 (macroexp-let2 macroexp-copyable-p temp form
2221 `(progn (unless (cl-typep ,temp ',type)
2222 (signal 'wrong-type-argument
2223 (list ',type ,temp ',form)))
2224 ,temp))))
2226 (defvar cl--proclaim-history t) ; for future compilers
2227 (defvar cl--declare-stack t) ; for future compilers
2229 (defun cl--do-proclaim (spec hist)
2230 (and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
2231 (cond ((eq (car-safe spec) 'special)
2232 (if (boundp 'byte-compile-bound-variables)
2233 (setq byte-compile-bound-variables
2234 (append (cdr spec) byte-compile-bound-variables))))
2236 ((eq (car-safe spec) 'inline)
2237 (while (setq spec (cdr spec))
2238 (or (memq (get (car spec) 'byte-optimizer)
2239 '(nil byte-compile-inline-expand))
2240 (error "%s already has a byte-optimizer, can't make it inline"
2241 (car spec)))
2242 (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
2244 ((eq (car-safe spec) 'notinline)
2245 (while (setq spec (cdr spec))
2246 (if (eq (get (car spec) 'byte-optimizer)
2247 'byte-compile-inline-expand)
2248 (put (car spec) 'byte-optimizer nil))))
2250 ((eq (car-safe spec) 'optimize)
2251 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
2252 '((0 nil) (1 t) (2 t) (3 t))))
2253 (safety (assq (nth 1 (assq 'safety (cdr spec)))
2254 '((0 t) (1 t) (2 t) (3 nil)))))
2255 (if speed (setq cl--optimize-speed (car speed)
2256 byte-optimize (nth 1 speed)))
2257 (if safety (setq cl--optimize-safety (car safety)
2258 byte-compile-delete-errors (nth 1 safety)))))
2260 ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
2261 (while (setq spec (cdr spec))
2262 (if (consp (car spec))
2263 (if (eq (cl-cadar spec) 0)
2264 (byte-compile-disable-warning (caar spec))
2265 (byte-compile-enable-warning (caar spec)))))))
2266 nil)
2268 ;;; Process any proclamations made before cl-macs was loaded.
2269 (defvar cl--proclaims-deferred)
2270 (let ((p (reverse cl--proclaims-deferred)))
2271 (while p (cl--do-proclaim (pop p) t))
2272 (setq cl--proclaims-deferred nil))
2274 ;;;###autoload
2275 (defmacro cl-declare (&rest specs)
2276 "Declare SPECS about the current function while compiling.
2277 For instance
2279 (cl-declare (warn 0))
2281 will turn off byte-compile warnings in the function.
2282 See Info node `(cl)Declarations' for details."
2283 (if (cl--compiling-file)
2284 (while specs
2285 (if (listp cl--declare-stack) (push (car specs) cl--declare-stack))
2286 (cl--do-proclaim (pop specs) nil)))
2287 nil)
2289 ;;; The standard modify macros.
2291 ;; `setf' is now part of core Elisp, defined in gv.el.
2293 ;;;###autoload
2294 (defmacro cl-psetf (&rest args)
2295 "Set PLACEs to the values VALs in parallel.
2296 This is like `setf', except that all VAL forms are evaluated (in order)
2297 before assigning any PLACEs to the corresponding values.
2299 \(fn PLACE VAL PLACE VAL ...)"
2300 (declare (debug setf))
2301 (let ((p args) (simple t) (vars nil))
2302 (while p
2303 (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
2304 (setq simple nil))
2305 (if (memq (car p) vars)
2306 (error "Destination duplicated in psetf: %s" (car p)))
2307 (push (pop p) vars)
2308 (or p (error "Odd number of arguments to cl-psetf"))
2309 (pop p))
2310 (if simple
2311 `(progn (setq ,@args) nil)
2312 (setq args (reverse args))
2313 (let ((expr `(setf ,(cadr args) ,(car args))))
2314 (while (setq args (cddr args))
2315 (setq expr `(setf ,(cadr args) (prog1 ,(car args) ,expr))))
2316 `(progn ,expr nil)))))
2318 ;;;###autoload
2319 (defmacro cl-remf (place tag)
2320 "Remove TAG from property list PLACE.
2321 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2322 The form returns true if TAG was found and removed, nil otherwise."
2323 (declare (debug (place form)))
2324 (gv-letplace (tval setter) place
2325 (macroexp-let2 macroexp-copyable-p ttag tag
2326 `(if (eq ,ttag (car ,tval))
2327 (progn ,(funcall setter `(cddr ,tval))
2329 (cl--do-remf ,tval ,ttag)))))
2331 ;;;###autoload
2332 (defmacro cl-shiftf (place &rest args)
2333 "Shift left among PLACEs.
2334 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2335 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2337 \(fn PLACE... VAL)"
2338 (declare (debug (&rest place)))
2339 (cond
2340 ((null args) place)
2341 ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
2343 (gv-letplace (getter setter) place
2344 `(prog1 ,getter
2345 ,(funcall setter `(cl-shiftf ,@args)))))))
2347 ;;;###autoload
2348 (defmacro cl-rotatef (&rest args)
2349 "Rotate left among PLACEs.
2350 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2351 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2353 \(fn PLACE...)"
2354 (declare (debug (&rest place)))
2355 (if (not (memq nil (mapcar 'symbolp args)))
2356 (and (cdr args)
2357 (let ((sets nil)
2358 (first (car args)))
2359 (while (cdr args)
2360 (setq sets (nconc sets (list (pop args) (car args)))))
2361 `(cl-psetf ,@sets ,(car args) ,first)))
2362 (let* ((places (reverse args))
2363 (temp (make-symbol "--cl-rotatef--"))
2364 (form temp))
2365 (while (cdr places)
2366 (setq form
2367 (gv-letplace (getter setter) (pop places)
2368 `(prog1 ,getter ,(funcall setter form)))))
2369 (gv-letplace (getter setter) (car places)
2370 (macroexp-let* `((,temp ,getter))
2371 `(progn ,(funcall setter form) nil))))))
2373 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2374 ;; previous state. If the getter/setter loses information, that info is
2375 ;; not recovered.
2377 (defun cl--letf (bindings simplebinds binds body)
2378 ;; It's not quite clear what the semantics of cl-letf should be.
2379 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2380 ;; that the actual assignments ("bindings") should only happen after
2381 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2382 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2383 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2384 ;; or
2385 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2386 ;; or
2387 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2388 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2389 (if (null bindings)
2390 (if (and (null binds) (null simplebinds)) (macroexp-progn body)
2391 `(let* (,@(mapcar (lambda (x)
2392 (pcase-let ((`(,vold ,getter ,_setter ,_vnew) x))
2393 (list vold getter)))
2394 binds)
2395 ,@simplebinds)
2396 (unwind-protect
2397 ,(macroexp-progn
2398 (append
2399 (delq nil
2400 (mapcar (lambda (x)
2401 (pcase x
2402 ;; If there's no vnew, do nothing.
2403 (`(,_vold ,_getter ,setter ,vnew)
2404 (funcall setter vnew))))
2405 binds))
2406 body))
2407 ,@(mapcar (lambda (x)
2408 (pcase-let ((`(,vold ,_getter ,setter ,_vnew) x))
2409 (funcall setter vold)))
2410 binds))))
2411 (let ((binding (car bindings)))
2412 (gv-letplace (getter setter) (car binding)
2413 (macroexp-let2 nil vnew (cadr binding)
2414 (if (symbolp (car binding))
2415 ;; Special-case for simple variables.
2416 (cl--letf (cdr bindings)
2417 (cons `(,getter ,(if (cdr binding) vnew getter))
2418 simplebinds)
2419 binds body)
2420 (cl--letf (cdr bindings) simplebinds
2421 (cons `(,(make-symbol "old") ,getter ,setter
2422 ,@(if (cdr binding) (list vnew)))
2423 binds)
2424 body)))))))
2426 ;;;###autoload
2427 (defmacro cl-letf (bindings &rest body)
2428 "Temporarily bind to PLACEs.
2429 This is the analogue of `let', but with generalized variables (in the
2430 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2431 VALUE, then the BODY forms are executed. On exit, either normally or
2432 because of a `throw' or error, the PLACEs are set back to their original
2433 values. Note that this macro is *not* available in Common Lisp.
2434 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2435 the PLACE is not modified before executing BODY.
2437 \(fn ((PLACE VALUE) ...) BODY...)"
2438 (declare (indent 1) (debug ((&rest (gate gv-place &optional form)) body)))
2439 (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2440 `(let ,bindings ,@body)
2441 (cl--letf bindings () () body)))
2443 ;;;###autoload
2444 (defmacro cl-letf* (bindings &rest body)
2445 "Temporarily bind to PLACEs.
2446 Like `cl-letf' but where the bindings are performed one at a time,
2447 rather than all at the end (i.e. like `let*' rather than like `let')."
2448 (declare (indent 1) (debug cl-letf))
2449 (dolist (binding (reverse bindings))
2450 (setq body (list `(cl-letf (,binding) ,@body))))
2451 (macroexp-progn body))
2453 ;;;###autoload
2454 (defmacro cl-callf (func place &rest args)
2455 "Set PLACE to (FUNC PLACE ARGS...).
2456 FUNC should be an unquoted function name. PLACE may be a symbol,
2457 or any generalized variable allowed by `setf'."
2458 (declare (indent 2) (debug (cl-function place &rest form)))
2459 (gv-letplace (getter setter) place
2460 (let* ((rargs (cons getter args)))
2461 (funcall setter
2462 (if (symbolp func) (cons func rargs)
2463 `(funcall #',func ,@rargs))))))
2465 ;;;###autoload
2466 (defmacro cl-callf2 (func arg1 place &rest args)
2467 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2468 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2470 \(fn FUNC ARG1 PLACE ARGS...)"
2471 (declare (indent 3) (debug (cl-function form place &rest form)))
2472 (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
2473 `(setf ,place (,func ,arg1 ,place ,@args))
2474 (macroexp-let2 nil a1 arg1
2475 (gv-letplace (getter setter) place
2476 (let* ((rargs (cl-list* a1 getter args)))
2477 (funcall setter
2478 (if (symbolp func) (cons func rargs)
2479 `(funcall #',func ,@rargs))))))))
2481 ;;;###autoload
2482 (defmacro cl-defsubst (name args &rest body)
2483 "Define NAME as a function.
2484 Like `defun', except the function is automatically declared `inline' and
2485 the arguments are immutable.
2486 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2487 surrounded by (cl-block NAME ...).
2488 The function's arguments should be treated as immutable.
2490 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2491 (declare (debug cl-defun) (indent 2))
2492 (let* ((argns (cl--arglist-args args))
2493 (real-args (if (eq '&cl-defs (car args)) (cddr args) args))
2494 (p argns)
2495 ;; (pbody (cons 'progn body))
2497 (while (and p (eq (cl--expr-contains real-args (car p)) 1)) (pop p))
2498 `(progn
2499 ,(if p nil ; give up if defaults refer to earlier args
2500 `(cl-define-compiler-macro ,name
2501 ,(if (memq '&key args)
2502 `(&whole cl-whole &cl-quote ,@args)
2503 (cons '&cl-quote args))
2504 (cl--defsubst-expand
2505 ',argns '(cl-block ,name ,@body)
2506 ;; We used to pass `simple' as
2507 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2508 ;; But this is much too simplistic since it
2509 ;; does not pay attention to the argvs (and
2510 ;; cl-expr-access-order itself is also too naive).
2512 ,(and (memq '&key args) 'cl-whole) nil ,@argns)))
2513 (cl-defun ,name ,args ,@body))))
2515 (defun cl--defsubst-expand (argns body simple whole _unsafe &rest argvs)
2516 (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
2517 (if (cl--simple-exprs-p argvs) (setq simple t))
2518 (let* ((substs ())
2519 (lets (delq nil
2520 (cl-mapcar (lambda (argn argv)
2521 (if (or simple (macroexp-const-p argv))
2522 (progn (push (cons argn argv) substs)
2523 nil)
2524 (list argn argv)))
2525 argns argvs))))
2526 ;; FIXME: `sublis/subst' will happily substitute the symbol
2527 ;; `argn' in places where it's not used as a reference
2528 ;; to a variable.
2529 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2530 ;; scope, leading to name capture.
2531 (setq body (cond ((null substs) body)
2532 ((null (cdr substs))
2533 (cl-subst (cdar substs) (caar substs) body))
2534 (t (cl--sublis substs body))))
2535 (if lets `(let ,lets ,body) body))))
2537 (defun cl--sublis (alist tree)
2538 "Perform substitutions indicated by ALIST in TREE (non-destructively)."
2539 (let ((x (assq tree alist)))
2540 (cond
2541 (x (cdr x))
2542 ((consp tree)
2543 (cons (cl--sublis alist (car tree)) (cl--sublis alist (cdr tree))))
2544 (t tree))))
2546 ;;; Structures.
2548 (defmacro cl--find-class (type)
2549 `(get ,type 'cl--class))
2551 ;; Rather than hard code cl-structure-object, we indirect through this variable
2552 ;; for bootstrapping reasons.
2553 (defvar cl--struct-default-parent nil)
2555 ;;;###autoload
2556 (defmacro cl-defstruct (struct &rest descs)
2557 "Define a struct type.
2558 This macro defines a new data type called NAME that stores data
2559 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2560 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2561 You can use the accessors to set the corresponding slots, via `setf'.
2563 NAME may instead take the form (NAME OPTIONS...), where each
2564 OPTION is either a single keyword or (KEYWORD VALUE) where
2565 KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
2566 :type, :named, :initial-offset, :print-function, or :include.
2568 Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
2569 SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
2570 pairs for that slot.
2571 Currently, only one keyword is supported, `:read-only'. If this has a
2572 non-nil value, that slot cannot be set via `setf'.
2574 \(fn NAME SLOTS...)"
2575 (declare (doc-string 2) (indent 1)
2576 (debug
2577 (&define ;Makes top-level form not be wrapped.
2578 [&or symbolp
2579 (gate
2580 symbolp &rest
2581 [&or symbolp
2582 (&or [":conc-name" symbolp]
2583 [":constructor" symbolp &optional cl-lambda-list]
2584 [":copier" symbolp]
2585 [":predicate" symbolp]
2586 [":include" symbolp &rest sexp] ;; Not finished.
2587 [":print-function" sexp]
2588 [":type" symbolp]
2589 [":named"]
2590 [":initial-offset" natnump])])]
2591 [&optional stringp]
2592 ;; All the above is for the following def-form.
2593 &rest &or symbolp (symbolp &optional def-form &rest sexp))))
2594 (let* ((name (if (consp struct) (car struct) struct))
2595 (opts (cdr-safe struct))
2596 (slots nil)
2597 (defaults nil)
2598 (conc-name (concat (symbol-name name) "-"))
2599 (constructor (intern (format "make-%s" name)))
2600 (constrs nil)
2601 (copier (intern (format "copy-%s" name)))
2602 (predicate (intern (format "%s-p" name)))
2603 (print-func nil) (print-auto nil)
2604 (safety (if (cl--compiling-file) cl--optimize-safety 3))
2605 (include nil)
2606 (tag (intern (format "cl-struct-%s" name)))
2607 (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2608 (include-descs nil)
2609 (include-name nil)
2610 (type nil)
2611 (named nil)
2612 (forms nil)
2613 (docstring (if (stringp (car descs)) (pop descs)))
2614 pred-form pred-check)
2615 (setq descs (cons '(cl-tag-slot)
2616 (mapcar (function (lambda (x) (if (consp x) x (list x))))
2617 descs)))
2618 (while opts
2619 (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2620 (args (cdr-safe (pop opts))))
2621 (cond ((eq opt :conc-name)
2622 (if args
2623 (setq conc-name (if (car args)
2624 (symbol-name (car args)) ""))))
2625 ((eq opt :constructor)
2626 (if (cdr args)
2627 (progn
2628 ;; If this defines a constructor of the same name as
2629 ;; the default one, don't define the default.
2630 (if (eq (car args) constructor)
2631 (setq constructor nil))
2632 (push args constrs))
2633 (if args (setq constructor (car args)))))
2634 ((eq opt :copier)
2635 (if args (setq copier (car args))))
2636 ((eq opt :predicate)
2637 (if args (setq predicate (car args))))
2638 ((eq opt :include)
2639 ;; FIXME: Actually, we can include more than once as long as
2640 ;; we include EIEIO classes rather than cl-structs!
2641 (when include-name (error "Can't :include more than once"))
2642 (setq include-name (car args))
2643 (setq include-descs (mapcar (function
2644 (lambda (x)
2645 (if (consp x) x (list x))))
2646 (cdr args))))
2647 ((eq opt :print-function)
2648 (setq print-func (car args)))
2649 ((eq opt :type)
2650 (setq type (car args)))
2651 ((eq opt :named)
2652 (setq named t))
2653 ((eq opt :initial-offset)
2654 (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2655 descs)))
2657 (error "Structure option %s unrecognized" opt)))))
2658 (unless (or include-name type)
2659 (setq include-name cl--struct-default-parent))
2660 (when include-name (setq include (cl--struct-get-class include-name)))
2661 (if print-func
2662 (setq print-func
2663 `(progn (funcall #',print-func cl-x cl-s cl-n) t))
2664 (or type (and include (not (cl--struct-class-print include)))
2665 (setq print-auto t
2666 print-func (and (or (not (or include type)) (null print-func))
2667 `(progn
2668 (princ ,(format "#S(%s" name) cl-s))))))
2669 (if include
2670 (let* ((inc-type (cl--struct-class-type include))
2671 (old-descs (cl-struct-slot-info include)))
2672 (and type (not (eq inc-type type))
2673 (error ":type disagrees with :include for %s" name))
2674 (while include-descs
2675 (setcar (memq (or (assq (caar include-descs) old-descs)
2676 (error "No slot %s in included struct %s"
2677 (caar include-descs) include))
2678 old-descs)
2679 (pop include-descs)))
2680 (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2681 type inc-type
2682 named (if type (assq 'cl-tag-slot descs) 'true))
2683 (if (cl--struct-class-named include) (setq tag name named t)))
2684 (if type
2685 (progn
2686 (or (memq type '(vector list))
2687 (error "Invalid :type specifier: %s" type))
2688 (if named (setq tag name)))
2689 (setq named 'true)))
2690 (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2691 (when (and (null predicate) named)
2692 (setq predicate (intern (format "cl--struct-%s-p" name))))
2693 (setq pred-form (and named
2694 (let ((pos (- (length descs)
2695 (length (memq (assq 'cl-tag-slot descs)
2696 descs)))))
2697 (cond
2698 ((memq type '(nil vector))
2699 `(and (vectorp cl-x)
2700 (>= (length cl-x) ,(length descs))
2701 (memq (aref cl-x ,pos) ,tag-symbol)))
2702 ((= pos 0) `(memq (car-safe cl-x) ,tag-symbol))
2703 (t `(and (consp cl-x)
2704 (memq (nth ,pos cl-x) ,tag-symbol))))))
2705 pred-check (and pred-form (> safety 0)
2706 (if (and (eq (cl-caadr pred-form) 'vectorp)
2707 (= safety 1))
2708 (cons 'and (cl-cdddr pred-form))
2709 `(,predicate cl-x))))
2710 (let ((pos 0) (descp descs))
2711 (while descp
2712 (let* ((desc (pop descp))
2713 (slot (pop desc)))
2714 (if (memq slot '(cl-tag-slot cl-skip-slot))
2715 (progn
2716 (push nil slots)
2717 (push (and (eq slot 'cl-tag-slot) `',tag)
2718 defaults))
2719 (if (assq slot descp)
2720 (error "Duplicate slots named %s in %s" slot name))
2721 (let ((accessor (intern (format "%s%s" conc-name slot))))
2722 (push slot slots)
2723 (push (pop desc) defaults)
2724 ;; The arg "cl-x" is referenced by name in eg pred-form
2725 ;; and pred-check, so changing it is not straightforward.
2726 (push `(cl-defsubst ,accessor (cl-x)
2727 ,(format "Access slot \"%s\" of `%s' struct CL-X."
2728 slot struct)
2729 (declare (side-effect-free t))
2730 ,@(and pred-check
2731 (list `(or ,pred-check
2732 (signal 'wrong-type-argument
2733 (list ',name cl-x)))))
2734 ,(if (memq type '(nil vector)) `(aref cl-x ,pos)
2735 (if (= pos 0) '(car cl-x)
2736 `(nth ,pos cl-x))))
2737 forms)
2738 (when (cl-oddp (length desc))
2739 (error "Invalid options for slot %s in %s" slot name))
2740 (if (plist-get desc ':read-only)
2741 (push `(gv-define-expander ,accessor
2742 (lambda (_cl-do _cl-x)
2743 (error "%s is a read-only slot" ',accessor)))
2744 forms)
2745 ;; For normal slots, we don't need to define a setf-expander,
2746 ;; since gv-get can use the compiler macro to get the
2747 ;; same result.
2748 ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
2749 ;; ;; If cl is loaded only for compilation,
2750 ;; ;; the call to cl--struct-setf-expander would
2751 ;; ;; cause a warning because it may not be
2752 ;; ;; defined at run time. Suppress that warning.
2753 ;; (progn
2754 ;; (declare-function
2755 ;; cl--struct-setf-expander "cl-macs"
2756 ;; (x name accessor pred-form pos))
2757 ;; (cl--struct-setf-expander
2758 ;; cl-val cl-x ',name ',accessor
2759 ;; ,(and pred-check `',pred-check)
2760 ;; ,pos)))
2761 ;; forms)
2763 (if print-auto
2764 (nconc print-func
2765 (list `(princ ,(format " %s" slot) cl-s)
2766 `(prin1 (,accessor cl-x) cl-s)))))))
2767 (setq pos (1+ pos))))
2768 (setq slots (nreverse slots)
2769 defaults (nreverse defaults))
2770 (when pred-form
2771 (push `(cl-defsubst ,predicate (cl-x)
2772 (declare (side-effect-free error-free))
2773 ,(if (eq (car pred-form) 'and)
2774 (append pred-form '(t))
2775 `(and ,pred-form t)))
2776 forms)
2777 (push `(put ',name 'cl-deftype-satisfies ',predicate) forms))
2778 (and copier
2779 (push `(defalias ',copier #'copy-sequence) forms))
2780 (if constructor
2781 (push (list constructor
2782 (cons '&key (delq nil (copy-sequence slots))))
2783 constrs))
2784 (pcase-dolist (`(,cname ,args ,doc) constrs)
2785 (let* ((anames (cl--arglist-args args))
2786 (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
2787 slots defaults)))
2788 (push `(cl-defsubst ,cname
2789 (&cl-defs (nil ,@descs) ,@args)
2790 ,(if (stringp doc) doc
2791 (format "Constructor for objects of type `%s'." name))
2792 ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
2793 '((declare (side-effect-free t))))
2794 (,(or type #'vector) ,@make))
2795 forms)))
2796 (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2797 ;; Don't bother adding to cl-custom-print-functions since it's not used
2798 ;; by anything anyway!
2799 ;;(if print-func
2800 ;; (push `(if (boundp 'cl-custom-print-functions)
2801 ;; (push
2802 ;; ;; The auto-generated function does not pay attention to
2803 ;; ;; the depth argument cl-n.
2804 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2805 ;; (and ,pred-form ,print-func))
2806 ;; cl-custom-print-functions))
2807 ;; forms))
2808 `(progn
2809 (defvar ,tag-symbol)
2810 ,@(nreverse forms)
2811 ;; Call cl-struct-define during compilation as well, so that
2812 ;; a subsequent cl-defstruct in the same file can correctly include this
2813 ;; struct as a parent.
2814 (eval-and-compile
2815 (cl-struct-define ',name ,docstring ',include-name
2816 ',type ,(eq named t) ',descs ',tag-symbol ',tag
2817 ',print-auto))
2818 ',name)))
2820 ;;; Add cl-struct support to pcase
2822 (defun cl--struct-all-parents (class)
2823 (when (cl--struct-class-p class)
2824 (let ((res ())
2825 (classes (list class)))
2826 ;; BFS precedence.
2827 (while (let ((class (pop classes)))
2828 (push class res)
2829 (setq classes
2830 (append classes
2831 (cl--class-parents class)))))
2832 (nreverse res))))
2834 ;;;###autoload
2835 (pcase-defmacro cl-struct (type &rest fields)
2836 "Pcase patterns to match cl-structs.
2837 Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
2838 field NAME is matched against PAT, or they can be of the form NAME which
2839 is a shorthand for (NAME NAME)."
2840 (declare (debug (sexp &rest [&or (sexp pcase-PAT) sexp])))
2841 `(and (pred (pcase--flip cl-typep ',type))
2842 ,@(mapcar
2843 (lambda (field)
2844 (let* ((name (if (consp field) (car field) field))
2845 (pat (if (consp field) (cadr field) field)))
2846 `(app ,(if (eq (cl-struct-sequence-type type) 'list)
2847 `(nth ,(cl-struct-slot-offset type name))
2848 `(pcase--flip aref ,(cl-struct-slot-offset type name)))
2849 ,pat)))
2850 fields)))
2852 (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2)
2853 "Extra special cases for `cl-typep' predicates."
2854 (let* ((x1 pred1) (x2 pred2)
2856 (and (eq 'pcase--flip (car-safe x1)) (setq x1 (cdr x1))
2857 (eq 'cl-typep (car-safe x1)) (setq x1 (cdr x1))
2858 (null (cdr-safe x1)) (setq x1 (car x1))
2859 (eq 'quote (car-safe x1)) (cadr x1)))
2861 (and (eq 'pcase--flip (car-safe x2)) (setq x2 (cdr x2))
2862 (eq 'cl-typep (car-safe x2)) (setq x2 (cdr x2))
2863 (null (cdr-safe x2)) (setq x2 (car x2))
2864 (eq 'quote (car-safe x2)) (cadr x2))))
2866 (and (symbolp t1) (symbolp t2)
2867 (let ((c1 (cl--find-class t1))
2868 (c2 (cl--find-class t2)))
2869 (and c1 c2
2870 (not (or (memq c1 (cl--struct-all-parents c2))
2871 (memq c2 (cl--struct-all-parents c1)))))))
2872 (let ((c1 (and (symbolp t1) (cl--find-class t1))))
2873 (and c1 (cl--struct-class-p c1)
2874 (funcall orig (if (eq 'list (cl-struct-sequence-type t1))
2875 'consp 'vectorp)
2876 pred2)))
2877 (let ((c2 (and (symbolp t2) (cl--find-class t2))))
2878 (and c2 (cl--struct-class-p c2)
2879 (funcall orig pred1
2880 (if (eq 'list (cl-struct-sequence-type t2))
2881 'consp 'vectorp))))
2882 (funcall orig pred1 pred2))))
2883 (advice-add 'pcase--mutually-exclusive-p
2884 :around #'cl--pcase-mutually-exclusive-p)
2887 (defun cl-struct-sequence-type (struct-type)
2888 "Return the sequence used to build STRUCT-TYPE.
2889 STRUCT-TYPE is a symbol naming a struct type. Return `vector' or
2890 `list', or nil if STRUCT-TYPE is not a struct type. "
2891 (declare (side-effect-free t) (pure t))
2892 (cl--struct-class-type (cl--struct-get-class struct-type)))
2894 (defun cl-struct-slot-info (struct-type)
2895 "Return a list of slot names of struct STRUCT-TYPE.
2896 Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
2897 slot name symbol and OPTS is a list of slot options given to
2898 `cl-defstruct'. Dummy slots that represent the struct name and
2899 slots skipped by :initial-offset may appear in the list."
2900 (declare (side-effect-free t) (pure t))
2901 (let* ((class (cl--struct-get-class struct-type))
2902 (slots (cl--struct-class-slots class))
2903 (type (cl--struct-class-type class))
2904 (descs (if type () (list '(cl-tag-slot)))))
2905 (dotimes (i (length slots))
2906 (let ((slot (aref slots i)))
2907 (push `(,(cl--slot-descriptor-name slot)
2908 ,(cl--slot-descriptor-initform slot)
2909 ,@(if (not (eq (cl--slot-descriptor-type slot) t))
2910 `(:type ,(cl--slot-descriptor-type slot)))
2911 ,@(cl--slot-descriptor-props slot))
2912 descs)))
2913 (nreverse descs)))
2915 (define-error 'cl-struct-unknown-slot "struct %S has no slot %S")
2917 (defun cl-struct-slot-offset (struct-type slot-name)
2918 "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
2919 The returned zero-based slot index is relative to the start of
2920 the structure data type and is adjusted for any structure name
2921 and :initial-offset slots. Signal error if struct STRUCT-TYPE
2922 does not contain SLOT-NAME."
2923 (declare (side-effect-free t) (pure t))
2924 (or (gethash slot-name
2925 (cl--class-index-table (cl--struct-get-class struct-type)))
2926 (signal 'cl-struct-unknown-slot (list struct-type slot-name))))
2928 (defvar byte-compile-function-environment)
2929 (defvar byte-compile-macro-environment)
2931 (defun cl--macroexp-fboundp (sym)
2932 "Return non-nil if SYM will be bound when we run the code.
2933 Of course, we really can't know that for sure, so it's just a heuristic."
2934 (or (fboundp sym)
2935 (and (cl--compiling-file)
2936 (or (cdr (assq sym byte-compile-function-environment))
2937 (cdr (assq sym byte-compile-macro-environment))))))
2939 (put 'null 'cl-deftype-satisfies #'null)
2940 (put 'atom 'cl-deftype-satisfies #'atom)
2941 (put 'real 'cl-deftype-satisfies #'numberp)
2942 (put 'fixnum 'cl-deftype-satisfies #'integerp)
2943 (put 'base-char 'cl-deftype-satisfies #'characterp)
2944 (put 'character 'cl-deftype-satisfies #'natnump)
2947 ;;;###autoload
2948 (define-inline cl-typep (val type)
2949 (inline-letevals (val)
2950 (pcase (inline-const-val type)
2951 ((and `(,name . ,args) (guard (get name 'cl-deftype-handler)))
2952 (inline-quote
2953 (cl-typep ,val ',(apply (get name 'cl-deftype-handler) args))))
2954 (`(,(and name (or 'integer 'float 'real 'number))
2955 . ,(or `(,min ,max) pcase--dontcare))
2956 (inline-quote
2957 (and (cl-typep ,val ',name)
2958 ,(if (memq min '(* nil)) t
2959 (if (consp min)
2960 (inline-quote (> ,val ',(car min)))
2961 (inline-quote (>= ,val ',min))))
2962 ,(if (memq max '(* nil)) t
2963 (if (consp max)
2964 (inline-quote (< ,val ',(car max)))
2965 (inline-quote (<= ,val ',max)))))))
2966 (`(not ,type) (inline-quote (not (cl-typep ,val ',type))))
2967 (`(,(and name (or 'and 'or)) . ,types)
2968 (cond
2969 ((null types) (inline-quote ',(eq name 'and)))
2970 ((null (cdr types))
2971 (inline-quote (cl-typep ,val ',(car types))))
2973 (let ((head (car types))
2974 (rest `(,name . ,(cdr types))))
2975 (cond
2976 ((eq name 'and)
2977 (inline-quote (and (cl-typep ,val ',head)
2978 (cl-typep ,val ',rest))))
2980 (inline-quote (or (cl-typep ,val ',head)
2981 (cl-typep ,val ',rest)))))))))
2982 (`(eql ,v) (inline-quote (and (eql ,val ',v) t)))
2983 (`(member . ,args) (inline-quote (and (memql ,val ',args) t)))
2984 (`(satisfies ,pred) (inline-quote (funcall #',pred ,val)))
2985 ((and (pred symbolp) type (guard (get type 'cl-deftype-handler)))
2986 (inline-quote
2987 (cl-typep ,val ',(funcall (get type 'cl-deftype-handler)))))
2988 ((and (pred symbolp) type (guard (get type 'cl-deftype-satisfies)))
2989 (inline-quote (funcall #',(get type 'cl-deftype-satisfies) ,val)))
2990 ((and (or 'nil 't) type) (inline-quote ',type))
2991 ((and (pred symbolp) type)
2992 (let* ((name (symbol-name type))
2993 (namep (intern (concat name "p"))))
2994 (cond
2995 ((cl--macroexp-fboundp namep) (inline-quote (funcall #',namep ,val)))
2996 ((cl--macroexp-fboundp
2997 (setq namep (intern (concat name "-p"))))
2998 (inline-quote (funcall #',namep ,val)))
2999 ((cl--macroexp-fboundp type) (inline-quote (funcall #',type ,val)))
3000 (t (error "Unknown type %S" type)))))
3001 (type (error "Bad type spec: %s" type)))))
3004 ;;;###autoload
3005 (defmacro cl-check-type (form type &optional string)
3006 "Verify that FORM is of type TYPE; signal an error if not.
3007 STRING is an optional description of the desired type."
3008 (declare (debug (place cl-type-spec &optional stringp)))
3009 (and (or (not (cl--compiling-file))
3010 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
3011 (macroexp-let2 macroexp-copyable-p temp form
3012 `(progn (or (cl-typep ,temp ',type)
3013 (signal 'wrong-type-argument
3014 (list ,(or string `',type) ,temp ',form)))
3015 nil))))
3017 ;;;###autoload
3018 (defmacro cl-assert (form &optional show-args string &rest args)
3019 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
3020 "Verify that FORM returns non-nil; signal an error if not.
3021 Second arg SHOW-ARGS means to include arguments of FORM in message.
3022 Other args STRING and ARGS... are arguments to be passed to `error'.
3023 They are not evaluated unless the assertion fails. If STRING is
3024 omitted, a default message listing FORM itself is used."
3025 (declare (debug (form &rest form)))
3026 (and (or (not (cl--compiling-file))
3027 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
3028 (let ((sargs (and show-args
3029 (delq nil (mapcar (lambda (x)
3030 (unless (macroexp-const-p x)
3032 (cdr-safe form))))))
3033 `(progn
3034 (or ,form
3035 (cl--assertion-failed
3036 ',form ,@(if (or string sargs args)
3037 `(,string (list ,@sargs) (list ,@args)))))
3038 nil))))
3040 ;;; Compiler macros.
3042 ;;;###autoload
3043 (defmacro cl-define-compiler-macro (func args &rest body)
3044 "Define a compiler-only macro.
3045 This is like `defmacro', but macro expansion occurs only if the call to
3046 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
3047 for optimizing the way calls to FUNC are compiled; the form returned by
3048 BODY should do the same thing as a call to the normal function called
3049 FUNC, though possibly more efficiently. Note that, like regular macros,
3050 compiler macros are expanded repeatedly until no further expansions are
3051 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
3052 original function call alone by declaring an initial `&whole foo' parameter
3053 and then returning foo."
3054 (declare (debug cl-defmacro) (indent 2))
3055 (let ((p args) (res nil))
3056 (while (consp p) (push (pop p) res))
3057 (setq args (nconc (nreverse res) (and p (list '&rest p)))))
3058 ;; FIXME: The code in bytecomp mishandles top-level expressions that define
3059 ;; uninterned functions. E.g. it would generate code like:
3060 ;; (defalias '#1=#:foo--cmacro #[514 ...])
3061 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
3062 ;; So we circumvent this by using an interned name.
3063 (let ((fname (intern (concat (symbol-name func) "--cmacro"))))
3064 `(eval-and-compile
3065 ;; Name the compiler-macro function, so that `symbol-file' can find it.
3066 (cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
3067 (cons '_cl-whole-arg args))
3068 ,@body)
3069 (put ',func 'compiler-macro #',fname))))
3071 ;;;###autoload
3072 (defun cl-compiler-macroexpand (form)
3073 "Like `macroexpand', but for compiler macros.
3074 Expands FORM repeatedly until no further expansion is possible.
3075 Returns FORM unchanged if it has no compiler macro, or if it has a
3076 macro that returns its `&whole' argument."
3077 (while
3078 (let ((func (car-safe form)) (handler nil))
3079 (while (and (symbolp func)
3080 (not (setq handler (get func 'compiler-macro)))
3081 (fboundp func)
3082 (or (not (autoloadp (symbol-function func)))
3083 (autoload-do-load (symbol-function func) func)))
3084 (setq func (symbol-function func)))
3085 (and handler
3086 (not (eq form (setq form (apply handler form (cdr form))))))))
3087 form)
3089 ;; Optimize away unused block-wrappers.
3091 (defvar cl--active-block-names nil)
3093 (cl-define-compiler-macro cl--block-wrapper (cl-form)
3094 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
3095 (cl--active-block-names (cons cl-entry cl--active-block-names))
3096 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
3097 (macroexp-progn (cddr cl-form))
3098 macroexpand-all-environment)))
3099 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
3100 ;; to indicate that this return value is already fully expanded.
3101 (if (cdr cl-entry)
3102 `(catch ,(nth 1 cl-form) ,@(macroexp-unprogn cl-body))
3103 cl-body)))
3105 (cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
3106 (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
3107 (if cl-found (setcdr cl-found t)))
3108 `(throw ,cl-tag ,cl-value))
3110 ;; Compile-time optimizations for some functions defined in this package.
3112 (defun cl--compiler-macro-member (form a list &rest keys)
3113 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3114 (cl--const-expr-val (nth 1 keys)))))
3115 (cond ((eq test 'eq) `(memq ,a ,list))
3116 ((eq test 'equal) `(member ,a ,list))
3117 ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
3118 (t form))))
3120 (defun cl--compiler-macro-assoc (form a list &rest keys)
3121 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3122 (cl--const-expr-val (nth 1 keys)))))
3123 (cond ((eq test 'eq) `(assq ,a ,list))
3124 ((eq test 'equal) `(assoc ,a ,list))
3125 ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
3126 (if (floatp (cl--const-expr-val a))
3127 `(assoc ,a ,list) `(assq ,a ,list)))
3128 (t form))))
3130 ;;;###autoload
3131 (defun cl--compiler-macro-adjoin (form a list &rest keys)
3132 (if (memq :key keys) form
3133 (macroexp-let2* macroexp-copyable-p ((va a) (vlist list))
3134 `(if (cl-member ,va ,vlist ,@keys) ,vlist (cons ,va ,vlist)))))
3136 (defun cl--compiler-macro-get (_form sym prop &optional def)
3137 (if def
3138 `(cl-getf (symbol-plist ,sym) ,prop ,def)
3139 `(get ,sym ,prop)))
3141 (dolist (y '(cl-first cl-second cl-third cl-fourth
3142 cl-fifth cl-sixth cl-seventh
3143 cl-eighth cl-ninth cl-tenth
3144 cl-rest cl-endp cl-plusp cl-minusp
3145 cl-caaar cl-caadr cl-cadar
3146 cl-caddr cl-cdaar cl-cdadr
3147 cl-cddar cl-cdddr cl-caaaar
3148 cl-caaadr cl-caadar cl-caaddr
3149 cl-cadaar cl-cadadr cl-caddar
3150 cl-cadddr cl-cdaaar cl-cdaadr
3151 cl-cdadar cl-cdaddr cl-cddaar
3152 cl-cddadr cl-cdddar cl-cddddr))
3153 (put y 'side-effect-free t))
3155 ;;; Things that are inline.
3156 (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
3157 cl-notevery cl-revappend cl-nreconc gethash))
3159 ;;; Things that are side-effect-free.
3160 (mapc (lambda (x) (function-put x 'side-effect-free t))
3161 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
3162 cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
3163 cl-subseq cl-list-length cl-get cl-getf))
3165 ;;; Things that are side-effect-and-error-free.
3166 (mapc (lambda (x) (function-put x 'side-effect-free 'error-free))
3167 '(eql cl-list* cl-subst cl-acons cl-equalp
3168 cl-random-state-p copy-tree cl-sublis))
3170 ;;; Types and assertions.
3172 ;;;###autoload
3173 (defmacro cl-deftype (name arglist &rest body)
3174 "Define NAME as a new data type.
3175 The type name can then be used in `cl-typecase', `cl-check-type', etc."
3176 (declare (debug cl-defmacro) (doc-string 3) (indent 2))
3177 `(cl-eval-when (compile load eval)
3178 (put ',name 'cl-deftype-handler
3179 (cl-function (lambda (&cl-defs ('*) ,@arglist) ,@body)))))
3181 (cl-deftype extended-char () `(and character (not base-char)))
3183 ;;; Additional functions that we can now define because we've defined
3184 ;;; `cl-defsubst' and `cl-typep'.
3186 (define-inline cl-struct-slot-value (struct-type slot-name inst)
3187 "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
3188 STRUCT and SLOT-NAME are symbols. INST is a structure instance."
3189 (declare (side-effect-free t))
3190 (inline-letevals (struct-type slot-name inst)
3191 (inline-quote
3192 (progn
3193 (unless (cl-typep ,inst ,struct-type)
3194 (signal 'wrong-type-argument (list ,struct-type ,inst)))
3195 ;; We could use `elt', but since the byte compiler will resolve the
3196 ;; branch below at compile time, it's more efficient to use the
3197 ;; type-specific accessor.
3198 (if (eq (cl-struct-sequence-type ,struct-type) 'list)
3199 (nth (cl-struct-slot-offset ,struct-type ,slot-name) ,inst)
3200 (aref ,inst (cl-struct-slot-offset ,struct-type ,slot-name)))))))
3202 (run-hooks 'cl-macs-load-hook)
3204 ;; Local variables:
3205 ;; byte-compile-dynamic: t
3206 ;; generated-autoload-file: "cl-loaddefs.el"
3207 ;; End:
3209 (provide 'cl-macs)
3211 ;;; cl-macs.el ends here