Improve skeleton docstrings
[emacs.git] / lisp / emacs-lisp / cl-macs.el
blobb3a60b1b225cb2df70dec97054c0c8646656bd44
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 ;;;###autoload
1841 (defmacro cl-do-symbols (spec &rest body)
1842 "Loop over all symbols.
1843 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1844 from OBARRAY.
1846 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1847 (declare (indent 1)
1848 (debug ((symbolp &optional form form) cl-declarations body)))
1849 ;; Apparently this doesn't have an implicit block.
1850 `(cl-block nil
1851 (let (,(car spec))
1852 (mapatoms #'(lambda (,(car spec)) ,@body)
1853 ,@(and (cadr spec) (list (cadr spec))))
1854 ,(nth 2 spec))))
1856 ;;;###autoload
1857 (defmacro cl-do-all-symbols (spec &rest body)
1858 "Like `cl-do-symbols', but use the default obarray.
1860 \(fn (VAR [RESULT]) BODY...)"
1861 (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
1862 `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
1865 ;;; Assignments.
1867 ;;;###autoload
1868 (defmacro cl-psetq (&rest args)
1869 "Set SYMs to the values VALs in parallel.
1870 This is like `setq', except that all VAL forms are evaluated (in order)
1871 before assigning any symbols SYM to the corresponding values.
1873 \(fn SYM VAL SYM VAL ...)"
1874 (declare (debug setq))
1875 (cons 'cl-psetf args))
1878 ;;; Binding control structures.
1880 ;;;###autoload
1881 (defmacro cl-progv (symbols values &rest body)
1882 "Bind SYMBOLS to VALUES dynamically in BODY.
1883 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1884 Each symbol in the first list is bound to the corresponding value in the
1885 second list (or to nil if VALUES is shorter than SYMBOLS); then the
1886 BODY forms are executed and their result is returned. This is much like
1887 a `let' form, except that the list of symbols can be computed at run-time."
1888 (declare (indent 2) (debug (form form body)))
1889 (let ((bodyfun (make-symbol "body"))
1890 (binds (make-symbol "binds"))
1891 (syms (make-symbol "syms"))
1892 (vals (make-symbol "vals")))
1893 `(progn
1894 (let* ((,syms ,symbols)
1895 (,vals ,values)
1896 (,bodyfun (lambda () ,@body))
1897 (,binds ()))
1898 (while ,syms
1899 (push (list (pop ,syms) (list 'quote (pop ,vals))) ,binds))
1900 (eval (list 'let ,binds (list 'funcall (list 'quote ,bodyfun))))))))
1902 (defconst cl--labels-magic (make-symbol "cl--labels-magic"))
1904 (defvar cl--labels-convert-cache nil)
1906 (defun cl--labels-convert (f)
1907 "Special macro-expander to rename (function F) references in `cl-labels'."
1908 (cond
1909 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1910 ;; *after* handling `function', but we want to stop macroexpansion from
1911 ;; being applied infinitely, so we use a cache to return the exact `form'
1912 ;; being expanded even though we don't receive it.
1913 ((eq f (car cl--labels-convert-cache)) (cdr cl--labels-convert-cache))
1915 (let* ((found (assq f macroexpand-all-environment))
1916 (replacement (and found
1917 (ignore-errors
1918 (funcall (cdr found) cl--labels-magic)))))
1919 (if (and replacement (eq cl--labels-magic (car replacement)))
1920 (nth 1 replacement)
1921 (let ((res `(function ,f)))
1922 (setq cl--labels-convert-cache (cons f res))
1923 res))))))
1925 ;;;###autoload
1926 (defmacro cl-flet (bindings &rest body)
1927 "Make local function definitions.
1928 Like `cl-labels' but the definitions are not recursive.
1929 Each binding can take the form (FUNC EXP) where
1930 FUNC is the function name, and EXP is an expression that returns the
1931 function value to which it should be bound, or it can take the more common
1932 form \(FUNC ARGLIST BODY...) which is a shorthand
1933 for (FUNC (lambda ARGLIST BODY)).
1935 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1936 (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
1937 (let ((binds ()) (newenv macroexpand-all-environment))
1938 (dolist (binding bindings)
1939 (let ((var (make-symbol (format "--cl-%s--" (car binding))))
1940 (args-and-body (cdr binding)))
1941 (if (and (= (length args-and-body) 1) (symbolp (car args-and-body)))
1942 ;; Optimize (cl-flet ((fun var)) body).
1943 (setq var (car args-and-body))
1944 (push (list var (if (= (length args-and-body) 1)
1945 (car args-and-body)
1946 `(cl-function (lambda . ,args-and-body))))
1947 binds))
1948 (push (cons (car binding)
1949 (lambda (&rest args)
1950 (if (eq (car args) cl--labels-magic)
1951 (list cl--labels-magic var)
1952 `(funcall ,var ,@args))))
1953 newenv)))
1954 ;; FIXME: Eliminate those functions which aren't referenced.
1955 (macroexp-let* (nreverse binds)
1956 (macroexpand-all
1957 `(progn ,@body)
1958 ;; Don't override lexical-let's macro-expander.
1959 (if (assq 'function newenv) newenv
1960 (cons (cons 'function #'cl--labels-convert) newenv))))))
1962 ;;;###autoload
1963 (defmacro cl-flet* (bindings &rest body)
1964 "Make local function definitions.
1965 Like `cl-flet' but the definitions can refer to previous ones.
1967 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1968 (declare (indent 1) (debug cl-flet))
1969 (cond
1970 ((null bindings) (macroexp-progn body))
1971 ((null (cdr bindings)) `(cl-flet ,bindings ,@body))
1972 (t `(cl-flet (,(pop bindings)) (cl-flet* ,bindings ,@body)))))
1974 ;;;###autoload
1975 (defmacro cl-labels (bindings &rest body)
1976 "Make temporary function bindings.
1977 The bindings can be recursive and the scoping is lexical, but capturing them
1978 in closures will only work if `lexical-binding' is in use.
1980 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1981 (declare (indent 1) (debug cl-flet))
1982 (let ((binds ()) (newenv macroexpand-all-environment))
1983 (dolist (binding bindings)
1984 (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
1985 (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
1986 (push (cons (car binding)
1987 (lambda (&rest args)
1988 (if (eq (car args) cl--labels-magic)
1989 (list cl--labels-magic var)
1990 (cl-list* 'funcall var args))))
1991 newenv)))
1992 (macroexpand-all `(letrec ,(nreverse binds) ,@body)
1993 ;; Don't override lexical-let's macro-expander.
1994 (if (assq 'function newenv) newenv
1995 (cons (cons 'function #'cl--labels-convert) newenv)))))
1997 ;; The following ought to have a better definition for use with newer
1998 ;; byte compilers.
1999 ;;;###autoload
2000 (defmacro cl-macrolet (bindings &rest body)
2001 "Make temporary macro definitions.
2002 This is like `cl-flet', but for macros instead of functions.
2004 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
2005 (declare (indent 1)
2006 (debug
2007 ((&rest (&define name (&rest arg) cl-declarations-or-string
2008 def-body))
2009 cl-declarations body)))
2010 (if (cdr bindings)
2011 `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
2012 (if (null bindings) (macroexp-progn body)
2013 (let* ((name (caar bindings))
2014 (res (cl--transform-lambda (cdar bindings) name)))
2015 (eval (car res))
2016 (macroexpand-all (macroexp-progn body)
2017 (cons (cons name
2018 (eval `(cl-function (lambda ,@(cdr res))) t))
2019 macroexpand-all-environment))))))
2021 (defconst cl--old-macroexpand
2022 (if (and (boundp 'cl--old-macroexpand)
2023 (eq (symbol-function 'macroexpand)
2024 #'cl--sm-macroexpand))
2025 cl--old-macroexpand
2026 (symbol-function 'macroexpand)))
2028 (defun cl--sm-macroexpand (exp &optional env)
2029 "Special macro expander used inside `cl-symbol-macrolet'.
2030 This function replaces `macroexpand' during macro expansion
2031 of `cl-symbol-macrolet', and does the same thing as `macroexpand'
2032 except that it additionally expands symbol macros."
2033 (let ((macroexpand-all-environment env))
2034 (while
2035 (progn
2036 (setq exp (funcall cl--old-macroexpand exp env))
2037 (pcase exp
2038 ((pred symbolp)
2039 ;; Perform symbol-macro expansion.
2040 (when (cdr (assq (symbol-name exp) env))
2041 (setq exp (cadr (assq (symbol-name exp) env)))))
2042 (`(setq . ,_)
2043 ;; Convert setq to setf if required by symbol-macro expansion.
2044 (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env))
2045 (cdr exp)))
2046 (p args))
2047 (while (and p (symbolp (car p))) (setq p (cddr p)))
2048 (if p (setq exp (cons 'setf args))
2049 (setq exp (cons 'setq args))
2050 ;; Don't loop further.
2051 nil)))
2052 (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2053 ;; CL's symbol-macrolet treats re-bindings as candidates for
2054 ;; expansion (turning the let into a letf if needed), contrary to
2055 ;; Common-Lisp where such re-bindings hide the symbol-macro.
2056 (let ((letf nil) (found nil) (nbs ()))
2057 (dolist (binding bindings)
2058 (let* ((var (if (symbolp binding) binding (car binding)))
2059 (sm (assq (symbol-name var) env)))
2060 (push (if (not (cdr sm))
2061 binding
2062 (let ((nexp (cadr sm)))
2063 (setq found t)
2064 (unless (symbolp nexp) (setq letf t))
2065 (cons nexp (cdr-safe binding))))
2066 nbs)))
2067 (when found
2068 (setq exp `(,(if letf
2069 (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
2070 (car exp))
2071 ,(nreverse nbs)
2072 ,@body)))))
2073 ;; FIXME: The behavior of CL made sense in a dynamically scoped
2074 ;; language, but for lexical scoping, Common-Lisp's behavior might
2075 ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
2076 ;; lexical-let), so maybe we should adjust the behavior based on
2077 ;; the use of lexical-binding.
2078 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2079 ;; (let ((nbs ()) (found nil))
2080 ;; (dolist (binding bindings)
2081 ;; (let* ((var (if (symbolp binding) binding (car binding)))
2082 ;; (name (symbol-name var))
2083 ;; (val (and found (consp binding) (eq 'let* (car exp))
2084 ;; (list (macroexpand-all (cadr binding)
2085 ;; env)))))
2086 ;; (push (if (assq name env)
2087 ;; ;; This binding should hide its symbol-macro,
2088 ;; ;; but given the way macroexpand-all works, we
2089 ;; ;; can't prevent application of `env' to the
2090 ;; ;; sub-expressions, so we need to α-rename this
2091 ;; ;; variable instead.
2092 ;; (let ((nvar (make-symbol
2093 ;; (copy-sequence name))))
2094 ;; (setq found t)
2095 ;; (push (list name nvar) env)
2096 ;; (cons nvar (or val (cdr-safe binding))))
2097 ;; (if val (cons var val) binding))
2098 ;; nbs)))
2099 ;; (when found
2100 ;; (setq exp `(,(car exp)
2101 ;; ,(nreverse nbs)
2102 ;; ,@(macroexp-unprogn
2103 ;; (macroexpand-all (macroexp-progn body)
2104 ;; env)))))
2105 ;; nil))
2107 exp))
2109 ;;;###autoload
2110 (defmacro cl-symbol-macrolet (bindings &rest body)
2111 "Make symbol macro definitions.
2112 Within the body FORMs, references to the variable NAME will be replaced
2113 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
2115 \(fn ((NAME EXPANSION) ...) FORM...)"
2116 (declare (indent 1) (debug ((&rest (symbol sexp)) cl-declarations body)))
2117 (cond
2118 ((cdr bindings)
2119 `(cl-symbol-macrolet (,(car bindings))
2120 (cl-symbol-macrolet ,(cdr bindings) ,@body)))
2121 ((null bindings) (macroexp-progn body))
2123 (let ((previous-macroexpand (symbol-function 'macroexpand)))
2124 (unwind-protect
2125 (progn
2126 (fset 'macroexpand #'cl--sm-macroexpand)
2127 (let ((expansion
2128 ;; FIXME: For N bindings, this will traverse `body' N times!
2129 (macroexpand-all (macroexp-progn body)
2130 (cons (list (symbol-name (caar bindings))
2131 (cl-cadar bindings))
2132 macroexpand-all-environment))))
2133 (if (or (null (cdar bindings)) (cl-cddar bindings))
2134 (macroexp--warn-and-return
2135 (format-message "Malformed `cl-symbol-macrolet' binding: %S"
2136 (car bindings))
2137 expansion)
2138 expansion)))
2139 (fset 'macroexpand previous-macroexpand))))))
2141 ;;; Multiple values.
2143 ;;;###autoload
2144 (defmacro cl-multiple-value-bind (vars form &rest body)
2145 "Collect multiple return values.
2146 FORM must return a list; the BODY is then executed with the first N elements
2147 of this list bound (`let'-style) to each of the symbols SYM in turn. This
2148 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
2149 simulate true multiple return values. For compatibility, (cl-values A B C) is
2150 a synonym for (list A B C).
2152 \(fn (SYM...) FORM BODY)"
2153 (declare (indent 2) (debug ((&rest symbolp) form body)))
2154 (let ((temp (make-symbol "--cl-var--")) (n -1))
2155 `(let* ((,temp ,form)
2156 ,@(mapcar (lambda (v)
2157 (list v `(nth ,(setq n (1+ n)) ,temp)))
2158 vars))
2159 ,@body)))
2161 ;;;###autoload
2162 (defmacro cl-multiple-value-setq (vars form)
2163 "Collect multiple return values.
2164 FORM must return a list; the first N elements of this list are stored in
2165 each of the symbols SYM in turn. This is analogous to the Common Lisp
2166 `multiple-value-setq' macro, using lists to simulate true multiple return
2167 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
2169 \(fn (SYM...) FORM)"
2170 (declare (indent 1) (debug ((&rest symbolp) form)))
2171 (cond ((null vars) `(progn ,form nil))
2172 ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
2174 (let* ((temp (make-symbol "--cl-var--")) (n 0))
2175 `(let ((,temp ,form))
2176 (prog1 (setq ,(pop vars) (car ,temp))
2177 (setq ,@(apply #'nconc
2178 (mapcar (lambda (v)
2179 (list v `(nth ,(setq n (1+ n))
2180 ,temp)))
2181 vars)))))))))
2184 ;;; Declarations.
2186 ;;;###autoload
2187 (defmacro cl-locally (&rest body)
2188 "Equivalent to `progn'."
2189 (declare (debug t))
2190 (cons 'progn body))
2191 ;;;###autoload
2192 (defmacro cl-the (type form)
2193 "Return FORM. If type-checking is enabled, assert that it is of TYPE."
2194 (declare (indent 1) (debug (cl-type-spec form)))
2195 (if (not (or (not (cl--compiling-file))
2196 (< cl--optimize-speed 3)
2197 (= cl--optimize-safety 3)))
2198 form
2199 (macroexp-let2 macroexp-copyable-p temp form
2200 `(progn (unless (cl-typep ,temp ',type)
2201 (signal 'wrong-type-argument
2202 (list ',type ,temp ',form)))
2203 ,temp))))
2205 (defvar cl--proclaim-history t) ; for future compilers
2206 (defvar cl--declare-stack t) ; for future compilers
2208 (defun cl--do-proclaim (spec hist)
2209 (and hist (listp cl--proclaim-history) (push spec cl--proclaim-history))
2210 (cond ((eq (car-safe spec) 'special)
2211 (if (boundp 'byte-compile-bound-variables)
2212 (setq byte-compile-bound-variables
2213 (append (cdr spec) byte-compile-bound-variables))))
2215 ((eq (car-safe spec) 'inline)
2216 (while (setq spec (cdr spec))
2217 (or (memq (get (car spec) 'byte-optimizer)
2218 '(nil byte-compile-inline-expand))
2219 (error "%s already has a byte-optimizer, can't make it inline"
2220 (car spec)))
2221 (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
2223 ((eq (car-safe spec) 'notinline)
2224 (while (setq spec (cdr spec))
2225 (if (eq (get (car spec) 'byte-optimizer)
2226 'byte-compile-inline-expand)
2227 (put (car spec) 'byte-optimizer nil))))
2229 ((eq (car-safe spec) 'optimize)
2230 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
2231 '((0 nil) (1 t) (2 t) (3 t))))
2232 (safety (assq (nth 1 (assq 'safety (cdr spec)))
2233 '((0 t) (1 t) (2 t) (3 nil)))))
2234 (if speed (setq cl--optimize-speed (car speed)
2235 byte-optimize (nth 1 speed)))
2236 (if safety (setq cl--optimize-safety (car safety)
2237 byte-compile-delete-errors (nth 1 safety)))))
2239 ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
2240 (while (setq spec (cdr spec))
2241 (if (consp (car spec))
2242 (if (eq (cl-cadar spec) 0)
2243 (byte-compile-disable-warning (caar spec))
2244 (byte-compile-enable-warning (caar spec)))))))
2245 nil)
2247 ;;; Process any proclamations made before cl-macs was loaded.
2248 (defvar cl--proclaims-deferred)
2249 (let ((p (reverse cl--proclaims-deferred)))
2250 (while p (cl--do-proclaim (pop p) t))
2251 (setq cl--proclaims-deferred nil))
2253 ;;;###autoload
2254 (defmacro cl-declare (&rest specs)
2255 "Declare SPECS about the current function while compiling.
2256 For instance
2258 (cl-declare (warn 0))
2260 will turn off byte-compile warnings in the function.
2261 See Info node `(cl)Declarations' for details."
2262 (if (cl--compiling-file)
2263 (while specs
2264 (if (listp cl--declare-stack) (push (car specs) cl--declare-stack))
2265 (cl--do-proclaim (pop specs) nil)))
2266 nil)
2268 ;;; The standard modify macros.
2270 ;; `setf' is now part of core Elisp, defined in gv.el.
2272 ;;;###autoload
2273 (defmacro cl-psetf (&rest args)
2274 "Set PLACEs to the values VALs in parallel.
2275 This is like `setf', except that all VAL forms are evaluated (in order)
2276 before assigning any PLACEs to the corresponding values.
2278 \(fn PLACE VAL PLACE VAL ...)"
2279 (declare (debug setf))
2280 (let ((p args) (simple t) (vars nil))
2281 (while p
2282 (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
2283 (setq simple nil))
2284 (if (memq (car p) vars)
2285 (error "Destination duplicated in psetf: %s" (car p)))
2286 (push (pop p) vars)
2287 (or p (error "Odd number of arguments to cl-psetf"))
2288 (pop p))
2289 (if simple
2290 `(progn (setq ,@args) nil)
2291 (setq args (reverse args))
2292 (let ((expr `(setf ,(cadr args) ,(car args))))
2293 (while (setq args (cddr args))
2294 (setq expr `(setf ,(cadr args) (prog1 ,(car args) ,expr))))
2295 `(progn ,expr nil)))))
2297 ;;;###autoload
2298 (defmacro cl-remf (place tag)
2299 "Remove TAG from property list PLACE.
2300 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2301 The form returns true if TAG was found and removed, nil otherwise."
2302 (declare (debug (place form)))
2303 (gv-letplace (tval setter) place
2304 (macroexp-let2 macroexp-copyable-p ttag tag
2305 `(if (eq ,ttag (car ,tval))
2306 (progn ,(funcall setter `(cddr ,tval))
2308 (cl--do-remf ,tval ,ttag)))))
2310 ;;;###autoload
2311 (defmacro cl-shiftf (place &rest args)
2312 "Shift left among PLACEs.
2313 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2314 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2316 \(fn PLACE... VAL)"
2317 (declare (debug (&rest place)))
2318 (cond
2319 ((null args) place)
2320 ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
2322 (gv-letplace (getter setter) place
2323 `(prog1 ,getter
2324 ,(funcall setter `(cl-shiftf ,@args)))))))
2326 ;;;###autoload
2327 (defmacro cl-rotatef (&rest args)
2328 "Rotate left among PLACEs.
2329 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2330 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2332 \(fn PLACE...)"
2333 (declare (debug (&rest place)))
2334 (if (not (memq nil (mapcar 'symbolp args)))
2335 (and (cdr args)
2336 (let ((sets nil)
2337 (first (car args)))
2338 (while (cdr args)
2339 (setq sets (nconc sets (list (pop args) (car args)))))
2340 `(cl-psetf ,@sets ,(car args) ,first)))
2341 (let* ((places (reverse args))
2342 (temp (make-symbol "--cl-rotatef--"))
2343 (form temp))
2344 (while (cdr places)
2345 (setq form
2346 (gv-letplace (getter setter) (pop places)
2347 `(prog1 ,getter ,(funcall setter form)))))
2348 (gv-letplace (getter setter) (car places)
2349 (macroexp-let* `((,temp ,getter))
2350 `(progn ,(funcall setter form) nil))))))
2352 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2353 ;; previous state. If the getter/setter loses information, that info is
2354 ;; not recovered.
2356 (defun cl--letf (bindings simplebinds binds body)
2357 ;; It's not quite clear what the semantics of cl-letf should be.
2358 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2359 ;; that the actual assignments ("bindings") should only happen after
2360 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2361 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2362 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2363 ;; or
2364 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2365 ;; or
2366 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2367 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2368 (if (null bindings)
2369 (if (and (null binds) (null simplebinds)) (macroexp-progn body)
2370 `(let* (,@(mapcar (lambda (x)
2371 (pcase-let ((`(,vold ,getter ,_setter ,_vnew) x))
2372 (list vold getter)))
2373 binds)
2374 ,@simplebinds)
2375 (unwind-protect
2376 ,(macroexp-progn
2377 (append
2378 (delq nil
2379 (mapcar (lambda (x)
2380 (pcase x
2381 ;; If there's no vnew, do nothing.
2382 (`(,_vold ,_getter ,setter ,vnew)
2383 (funcall setter vnew))))
2384 binds))
2385 body))
2386 ,@(mapcar (lambda (x)
2387 (pcase-let ((`(,vold ,_getter ,setter ,_vnew) x))
2388 (funcall setter vold)))
2389 binds))))
2390 (let ((binding (car bindings)))
2391 (gv-letplace (getter setter) (car binding)
2392 (macroexp-let2 nil vnew (cadr binding)
2393 (if (symbolp (car binding))
2394 ;; Special-case for simple variables.
2395 (cl--letf (cdr bindings)
2396 (cons `(,getter ,(if (cdr binding) vnew getter))
2397 simplebinds)
2398 binds body)
2399 (cl--letf (cdr bindings) simplebinds
2400 (cons `(,(make-symbol "old") ,getter ,setter
2401 ,@(if (cdr binding) (list vnew)))
2402 binds)
2403 body)))))))
2405 ;;;###autoload
2406 (defmacro cl-letf (bindings &rest body)
2407 "Temporarily bind to PLACEs.
2408 This is the analogue of `let', but with generalized variables (in the
2409 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2410 VALUE, then the BODY forms are executed. On exit, either normally or
2411 because of a `throw' or error, the PLACEs are set back to their original
2412 values. Note that this macro is *not* available in Common Lisp.
2413 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2414 the PLACE is not modified before executing BODY.
2416 \(fn ((PLACE VALUE) ...) BODY...)"
2417 (declare (indent 1) (debug ((&rest (gate gv-place &optional form)) body)))
2418 (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2419 `(let ,bindings ,@body)
2420 (cl--letf bindings () () body)))
2422 ;;;###autoload
2423 (defmacro cl-letf* (bindings &rest body)
2424 "Temporarily bind to PLACEs.
2425 Like `cl-letf' but where the bindings are performed one at a time,
2426 rather than all at the end (i.e. like `let*' rather than like `let')."
2427 (declare (indent 1) (debug cl-letf))
2428 (dolist (binding (reverse bindings))
2429 (setq body (list `(cl-letf (,binding) ,@body))))
2430 (macroexp-progn body))
2432 ;;;###autoload
2433 (defmacro cl-callf (func place &rest args)
2434 "Set PLACE to (FUNC PLACE ARGS...).
2435 FUNC should be an unquoted function name. PLACE may be a symbol,
2436 or any generalized variable allowed by `setf'."
2437 (declare (indent 2) (debug (cl-function place &rest form)))
2438 (gv-letplace (getter setter) place
2439 (let* ((rargs (cons getter args)))
2440 (funcall setter
2441 (if (symbolp func) (cons func rargs)
2442 `(funcall #',func ,@rargs))))))
2444 ;;;###autoload
2445 (defmacro cl-callf2 (func arg1 place &rest args)
2446 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2447 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2449 \(fn FUNC ARG1 PLACE ARGS...)"
2450 (declare (indent 3) (debug (cl-function form place &rest form)))
2451 (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
2452 `(setf ,place (,func ,arg1 ,place ,@args))
2453 (macroexp-let2 nil a1 arg1
2454 (gv-letplace (getter setter) place
2455 (let* ((rargs (cl-list* a1 getter args)))
2456 (funcall setter
2457 (if (symbolp func) (cons func rargs)
2458 `(funcall #',func ,@rargs))))))))
2460 ;;;###autoload
2461 (defmacro cl-defsubst (name args &rest body)
2462 "Define NAME as a function.
2463 Like `defun', except the function is automatically declared `inline' and
2464 the arguments are immutable.
2465 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2466 surrounded by (cl-block NAME ...).
2467 The function's arguments should be treated as immutable.
2469 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2470 (declare (debug cl-defun) (indent 2))
2471 (let* ((argns (cl--arglist-args args))
2472 (real-args (if (eq '&cl-defs (car args)) (cddr args) args))
2473 (p argns)
2474 ;; (pbody (cons 'progn body))
2476 (while (and p (eq (cl--expr-contains real-args (car p)) 1)) (pop p))
2477 `(progn
2478 ,(if p nil ; give up if defaults refer to earlier args
2479 `(cl-define-compiler-macro ,name
2480 ,(if (memq '&key args)
2481 `(&whole cl-whole &cl-quote ,@args)
2482 (cons '&cl-quote args))
2483 (cl--defsubst-expand
2484 ',argns '(cl-block ,name ,@body)
2485 ;; We used to pass `simple' as
2486 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2487 ;; But this is much too simplistic since it
2488 ;; does not pay attention to the argvs (and
2489 ;; cl-expr-access-order itself is also too naive).
2491 ,(and (memq '&key args) 'cl-whole) nil ,@argns)))
2492 (cl-defun ,name ,args ,@body))))
2494 (defun cl--defsubst-expand (argns body simple whole _unsafe &rest argvs)
2495 (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
2496 (if (cl--simple-exprs-p argvs) (setq simple t))
2497 (let* ((substs ())
2498 (lets (delq nil
2499 (cl-mapcar (lambda (argn argv)
2500 (if (or simple (macroexp-const-p argv))
2501 (progn (push (cons argn argv) substs)
2502 nil)
2503 (list argn argv)))
2504 argns argvs))))
2505 ;; FIXME: `sublis/subst' will happily substitute the symbol
2506 ;; `argn' in places where it's not used as a reference
2507 ;; to a variable.
2508 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2509 ;; scope, leading to name capture.
2510 (setq body (cond ((null substs) body)
2511 ((null (cdr substs))
2512 (cl-subst (cdar substs) (caar substs) body))
2513 (t (cl--sublis substs body))))
2514 (if lets `(let ,lets ,body) body))))
2516 (defun cl--sublis (alist tree)
2517 "Perform substitutions indicated by ALIST in TREE (non-destructively)."
2518 (let ((x (assq tree alist)))
2519 (cond
2520 (x (cdr x))
2521 ((consp tree)
2522 (cons (cl--sublis alist (car tree)) (cl--sublis alist (cdr tree))))
2523 (t tree))))
2525 ;;; Structures.
2527 (defmacro cl--find-class (type)
2528 `(get ,type 'cl--class))
2530 ;; Rather than hard code cl-structure-object, we indirect through this variable
2531 ;; for bootstrapping reasons.
2532 (defvar cl--struct-default-parent nil)
2534 ;;;###autoload
2535 (defmacro cl-defstruct (struct &rest descs)
2536 "Define a struct type.
2537 This macro defines a new data type called NAME that stores data
2538 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2539 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2540 You can use the accessors to set the corresponding slots, via `setf'.
2542 NAME may instead take the form (NAME OPTIONS...), where each
2543 OPTION is either a single keyword or (KEYWORD VALUE) where
2544 KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
2545 :type, :named, :initial-offset, :print-function, or :include.
2547 Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
2548 SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
2549 pairs for that slot.
2550 Currently, only one keyword is supported, `:read-only'. If this has a
2551 non-nil value, that slot cannot be set via `setf'.
2553 \(fn NAME SLOTS...)"
2554 (declare (doc-string 2) (indent 1)
2555 (debug
2556 (&define ;Makes top-level form not be wrapped.
2557 [&or symbolp
2558 (gate
2559 symbolp &rest
2560 (&or [":conc-name" symbolp]
2561 [":constructor" symbolp &optional cl-lambda-list]
2562 [":copier" symbolp]
2563 [":predicate" symbolp]
2564 [":include" symbolp &rest sexp] ;; Not finished.
2565 ;; The following are not supported.
2566 ;; [":print-function" ...]
2567 ;; [":type" ...]
2568 ;; [":initial-offset" ...]
2570 [&optional stringp]
2571 ;; All the above is for the following def-form.
2572 &rest &or symbolp (symbolp def-form
2573 &optional ":read-only" sexp))))
2574 (let* ((name (if (consp struct) (car struct) struct))
2575 (opts (cdr-safe struct))
2576 (slots nil)
2577 (defaults nil)
2578 (conc-name (concat (symbol-name name) "-"))
2579 (constructor (intern (format "make-%s" name)))
2580 (constrs nil)
2581 (copier (intern (format "copy-%s" name)))
2582 (predicate (intern (format "%s-p" name)))
2583 (print-func nil) (print-auto nil)
2584 (safety (if (cl--compiling-file) cl--optimize-safety 3))
2585 (include nil)
2586 (tag (intern (format "cl-struct-%s" name)))
2587 (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2588 (include-descs nil)
2589 (include-name nil)
2590 (type nil)
2591 (named nil)
2592 (forms nil)
2593 (docstring (if (stringp (car descs)) (pop descs)))
2594 pred-form pred-check)
2595 (setq descs (cons '(cl-tag-slot)
2596 (mapcar (function (lambda (x) (if (consp x) x (list x))))
2597 descs)))
2598 (while opts
2599 (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2600 (args (cdr-safe (pop opts))))
2601 (cond ((eq opt :conc-name)
2602 (if args
2603 (setq conc-name (if (car args)
2604 (symbol-name (car args)) ""))))
2605 ((eq opt :constructor)
2606 (if (cdr args)
2607 (progn
2608 ;; If this defines a constructor of the same name as
2609 ;; the default one, don't define the default.
2610 (if (eq (car args) constructor)
2611 (setq constructor nil))
2612 (push args constrs))
2613 (if args (setq constructor (car args)))))
2614 ((eq opt :copier)
2615 (if args (setq copier (car args))))
2616 ((eq opt :predicate)
2617 (if args (setq predicate (car args))))
2618 ((eq opt :include)
2619 ;; FIXME: Actually, we can include more than once as long as
2620 ;; we include EIEIO classes rather than cl-structs!
2621 (when include-name (error "Can't :include more than once"))
2622 (setq include-name (car args))
2623 (setq include-descs (mapcar (function
2624 (lambda (x)
2625 (if (consp x) x (list x))))
2626 (cdr args))))
2627 ((eq opt :print-function)
2628 (setq print-func (car args)))
2629 ((eq opt :type)
2630 (setq type (car args)))
2631 ((eq opt :named)
2632 (setq named t))
2633 ((eq opt :initial-offset)
2634 (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2635 descs)))
2637 (error "Slot option %s unrecognized" opt)))))
2638 (unless (or include-name type)
2639 (setq include-name cl--struct-default-parent))
2640 (when include-name (setq include (cl--struct-get-class include-name)))
2641 (if print-func
2642 (setq print-func
2643 `(progn (funcall #',print-func cl-x cl-s cl-n) t))
2644 (or type (and include (not (cl--struct-class-print include)))
2645 (setq print-auto t
2646 print-func (and (or (not (or include type)) (null print-func))
2647 `(progn
2648 (princ ,(format "#S(%s" name) cl-s))))))
2649 (if include
2650 (let* ((inc-type (cl--struct-class-type include))
2651 (old-descs (cl-struct-slot-info include)))
2652 (and type (not (eq inc-type type))
2653 (error ":type disagrees with :include for %s" name))
2654 (while include-descs
2655 (setcar (memq (or (assq (caar include-descs) old-descs)
2656 (error "No slot %s in included struct %s"
2657 (caar include-descs) include))
2658 old-descs)
2659 (pop include-descs)))
2660 (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2661 type inc-type
2662 named (if type (assq 'cl-tag-slot descs) 'true))
2663 (if (cl--struct-class-named include) (setq tag name named t)))
2664 (if type
2665 (progn
2666 (or (memq type '(vector list))
2667 (error "Invalid :type specifier: %s" type))
2668 (if named (setq tag name)))
2669 (setq named 'true)))
2670 (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2671 (when (and (null predicate) named)
2672 (setq predicate (intern (format "cl--struct-%s-p" name))))
2673 (setq pred-form (and named
2674 (let ((pos (- (length descs)
2675 (length (memq (assq 'cl-tag-slot descs)
2676 descs)))))
2677 (cond
2678 ((memq type '(nil vector))
2679 `(and (vectorp cl-x)
2680 (>= (length cl-x) ,(length descs))
2681 (memq (aref cl-x ,pos) ,tag-symbol)))
2682 ((= pos 0) `(memq (car-safe cl-x) ,tag-symbol))
2683 (t `(and (consp cl-x)
2684 (memq (nth ,pos cl-x) ,tag-symbol))))))
2685 pred-check (and pred-form (> safety 0)
2686 (if (and (eq (cl-caadr pred-form) 'vectorp)
2687 (= safety 1))
2688 (cons 'and (cl-cdddr pred-form))
2689 `(,predicate cl-x))))
2690 (when pred-form
2691 (push `(cl-defsubst ,predicate (cl-x)
2692 (declare (side-effect-free error-free))
2693 ,(if (eq (car pred-form) 'and)
2694 (append pred-form '(t))
2695 `(and ,pred-form t)))
2696 forms)
2697 (push `(put ',name 'cl-deftype-satisfies ',predicate) forms))
2698 (let ((pos 0) (descp descs))
2699 (while descp
2700 (let* ((desc (pop descp))
2701 (slot (car desc)))
2702 (if (memq slot '(cl-tag-slot cl-skip-slot))
2703 (progn
2704 (push nil slots)
2705 (push (and (eq slot 'cl-tag-slot) `',tag)
2706 defaults))
2707 (if (assq slot descp)
2708 (error "Duplicate slots named %s in %s" slot name))
2709 (let ((accessor (intern (format "%s%s" conc-name slot))))
2710 (push slot slots)
2711 (push (nth 1 desc) defaults)
2712 (push `(cl-defsubst ,accessor (cl-x)
2713 (declare (side-effect-free t))
2714 ,@(and pred-check
2715 (list `(or ,pred-check
2716 (signal 'wrong-type-argument
2717 (list ',name cl-x)))))
2718 ,(if (memq type '(nil vector)) `(aref cl-x ,pos)
2719 (if (= pos 0) '(car cl-x)
2720 `(nth ,pos cl-x))))
2721 forms)
2722 (if (cadr (memq :read-only (cddr desc)))
2723 (push `(gv-define-expander ,accessor
2724 (lambda (_cl-do _cl-x)
2725 (error "%s is a read-only slot" ',accessor)))
2726 forms)
2727 ;; For normal slots, we don't need to define a setf-expander,
2728 ;; since gv-get can use the compiler macro to get the
2729 ;; same result.
2730 ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
2731 ;; ;; If cl is loaded only for compilation,
2732 ;; ;; the call to cl--struct-setf-expander would
2733 ;; ;; cause a warning because it may not be
2734 ;; ;; defined at run time. Suppress that warning.
2735 ;; (progn
2736 ;; (declare-function
2737 ;; cl--struct-setf-expander "cl-macs"
2738 ;; (x name accessor pred-form pos))
2739 ;; (cl--struct-setf-expander
2740 ;; cl-val cl-x ',name ',accessor
2741 ;; ,(and pred-check `',pred-check)
2742 ;; ,pos)))
2743 ;; forms)
2745 (if print-auto
2746 (nconc print-func
2747 (list `(princ ,(format " %s" slot) cl-s)
2748 `(prin1 (,accessor cl-x) cl-s)))))))
2749 (setq pos (1+ pos))))
2750 (setq slots (nreverse slots)
2751 defaults (nreverse defaults))
2752 (and copier
2753 (push `(defalias ',copier #'copy-sequence) forms))
2754 (if constructor
2755 (push (list constructor
2756 (cons '&key (delq nil (copy-sequence slots))))
2757 constrs))
2758 (pcase-dolist (`(,cname ,args ,doc) constrs)
2759 (let* ((anames (cl--arglist-args args))
2760 (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
2761 slots defaults)))
2762 (push `(cl-defsubst ,cname
2763 (&cl-defs (nil ,@descs) ,@args)
2764 ,(if (stringp doc) doc
2765 (format "Constructor for objects of type `%s'." name))
2766 ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
2767 '((declare (side-effect-free t))))
2768 (,(or type #'vector) ,@make))
2769 forms)))
2770 (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2771 ;; Don't bother adding to cl-custom-print-functions since it's not used
2772 ;; by anything anyway!
2773 ;;(if print-func
2774 ;; (push `(if (boundp 'cl-custom-print-functions)
2775 ;; (push
2776 ;; ;; The auto-generated function does not pay attention to
2777 ;; ;; the depth argument cl-n.
2778 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2779 ;; (and ,pred-form ,print-func))
2780 ;; cl-custom-print-functions))
2781 ;; forms))
2782 `(progn
2783 (defvar ,tag-symbol)
2784 ,@(nreverse forms)
2785 ;; Call cl-struct-define during compilation as well, so that
2786 ;; a subsequent cl-defstruct in the same file can correctly include this
2787 ;; struct as a parent.
2788 (eval-and-compile
2789 (cl-struct-define ',name ,docstring ',include-name
2790 ',type ,(eq named t) ',descs ',tag-symbol ',tag
2791 ',print-auto))
2792 ',name)))
2794 ;;; Add cl-struct support to pcase
2796 (defun cl--struct-all-parents (class)
2797 (when (cl--struct-class-p class)
2798 (let ((res ())
2799 (classes (list class)))
2800 ;; BFS precedence.
2801 (while (let ((class (pop classes)))
2802 (push class res)
2803 (setq classes
2804 (append classes
2805 (cl--class-parents class)))))
2806 (nreverse res))))
2808 ;;;###autoload
2809 (pcase-defmacro cl-struct (type &rest fields)
2810 "Pcase patterns to match cl-structs.
2811 Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
2812 field NAME is matched against PAT, or they can be of the form NAME which
2813 is a shorthand for (NAME NAME)."
2814 (declare (debug (sexp &rest [&or (sexp pcase-PAT) sexp])))
2815 `(and (pred (pcase--flip cl-typep ',type))
2816 ,@(mapcar
2817 (lambda (field)
2818 (let* ((name (if (consp field) (car field) field))
2819 (pat (if (consp field) (cadr field) field)))
2820 `(app ,(if (eq (cl-struct-sequence-type type) 'list)
2821 `(nth ,(cl-struct-slot-offset type name))
2822 `(pcase--flip aref ,(cl-struct-slot-offset type name)))
2823 ,pat)))
2824 fields)))
2826 (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2)
2827 "Extra special cases for `cl-typep' predicates."
2828 (let* ((x1 pred1) (x2 pred2)
2830 (and (eq 'pcase--flip (car-safe x1)) (setq x1 (cdr x1))
2831 (eq 'cl-typep (car-safe x1)) (setq x1 (cdr x1))
2832 (null (cdr-safe x1)) (setq x1 (car x1))
2833 (eq 'quote (car-safe x1)) (cadr x1)))
2835 (and (eq 'pcase--flip (car-safe x2)) (setq x2 (cdr x2))
2836 (eq 'cl-typep (car-safe x2)) (setq x2 (cdr x2))
2837 (null (cdr-safe x2)) (setq x2 (car x2))
2838 (eq 'quote (car-safe x2)) (cadr x2))))
2840 (and (symbolp t1) (symbolp t2)
2841 (let ((c1 (cl--find-class t1))
2842 (c2 (cl--find-class t2)))
2843 (and c1 c2
2844 (not (or (memq c1 (cl--struct-all-parents c2))
2845 (memq c2 (cl--struct-all-parents c1)))))))
2846 (let ((c1 (and (symbolp t1) (cl--find-class t1))))
2847 (and c1 (cl--struct-class-p c1)
2848 (funcall orig (if (eq 'list (cl-struct-sequence-type t1))
2849 'consp 'vectorp)
2850 pred2)))
2851 (let ((c2 (and (symbolp t2) (cl--find-class t2))))
2852 (and c2 (cl--struct-class-p c2)
2853 (funcall orig pred1
2854 (if (eq 'list (cl-struct-sequence-type t2))
2855 'consp 'vectorp))))
2856 (funcall orig pred1 pred2))))
2857 (advice-add 'pcase--mutually-exclusive-p
2858 :around #'cl--pcase-mutually-exclusive-p)
2861 (defun cl-struct-sequence-type (struct-type)
2862 "Return the sequence used to build STRUCT-TYPE.
2863 STRUCT-TYPE is a symbol naming a struct type. Return `vector' or
2864 `list', or nil if STRUCT-TYPE is not a struct type. "
2865 (declare (side-effect-free t) (pure t))
2866 (cl--struct-class-type (cl--struct-get-class struct-type)))
2868 (defun cl-struct-slot-info (struct-type)
2869 "Return a list of slot names of struct STRUCT-TYPE.
2870 Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
2871 slot name symbol and OPTS is a list of slot options given to
2872 `cl-defstruct'. Dummy slots that represent the struct name and
2873 slots skipped by :initial-offset may appear in the list."
2874 (declare (side-effect-free t) (pure t))
2875 (let* ((class (cl--struct-get-class struct-type))
2876 (slots (cl--struct-class-slots class))
2877 (type (cl--struct-class-type class))
2878 (descs (if type () (list '(cl-tag-slot)))))
2879 (dotimes (i (length slots))
2880 (let ((slot (aref slots i)))
2881 (push `(,(cl--slot-descriptor-name slot)
2882 ,(cl--slot-descriptor-initform slot)
2883 ,@(if (not (eq (cl--slot-descriptor-type slot) t))
2884 `(:type ,(cl--slot-descriptor-type slot)))
2885 ,@(cl--slot-descriptor-props slot))
2886 descs)))
2887 (nreverse descs)))
2889 (define-error 'cl-struct-unknown-slot "struct %S has no slot %S")
2891 (defun cl-struct-slot-offset (struct-type slot-name)
2892 "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
2893 The returned zero-based slot index is relative to the start of
2894 the structure data type and is adjusted for any structure name
2895 and :initial-offset slots. Signal error if struct STRUCT-TYPE
2896 does not contain SLOT-NAME."
2897 (declare (side-effect-free t) (pure t))
2898 (or (gethash slot-name
2899 (cl--class-index-table (cl--struct-get-class struct-type)))
2900 (signal 'cl-struct-unknown-slot (list struct-type slot-name))))
2902 (defvar byte-compile-function-environment)
2903 (defvar byte-compile-macro-environment)
2905 (defun cl--macroexp-fboundp (sym)
2906 "Return non-nil if SYM will be bound when we run the code.
2907 Of course, we really can't know that for sure, so it's just a heuristic."
2908 (or (fboundp sym)
2909 (and (cl--compiling-file)
2910 (or (cdr (assq sym byte-compile-function-environment))
2911 (cdr (assq sym byte-compile-macro-environment))))))
2913 (put 'null 'cl-deftype-satisfies #'null)
2914 (put 'atom 'cl-deftype-satisfies #'atom)
2915 (put 'real 'cl-deftype-satisfies #'numberp)
2916 (put 'fixnum 'cl-deftype-satisfies #'integerp)
2917 (put 'base-char 'cl-deftype-satisfies #'characterp)
2918 (put 'character 'cl-deftype-satisfies #'natnump)
2921 ;;;###autoload
2922 (define-inline cl-typep (val type)
2923 (inline-letevals (val)
2924 (pcase (inline-const-val type)
2925 ((and `(,name . ,args) (guard (get name 'cl-deftype-handler)))
2926 (inline-quote
2927 (cl-typep ,val ',(apply (get name 'cl-deftype-handler) args))))
2928 (`(,(and name (or 'integer 'float 'real 'number))
2929 . ,(or `(,min ,max) pcase--dontcare))
2930 (inline-quote
2931 (and (cl-typep ,val ',name)
2932 ,(if (memq min '(* nil)) t
2933 (if (consp min)
2934 (inline-quote (> ,val ',(car min)))
2935 (inline-quote (>= ,val ',min))))
2936 ,(if (memq max '(* nil)) t
2937 (if (consp max)
2938 (inline-quote (< ,val ',(car max)))
2939 (inline-quote (<= ,val ',max)))))))
2940 (`(not ,type) (inline-quote (not (cl-typep ,val ',type))))
2941 (`(,(and name (or 'and 'or)) . ,types)
2942 (cond
2943 ((null types) (inline-quote ',(eq name 'and)))
2944 ((null (cdr types))
2945 (inline-quote (cl-typep ,val ',(car types))))
2947 (let ((head (car types))
2948 (rest `(,name . ,(cdr types))))
2949 (cond
2950 ((eq name 'and)
2951 (inline-quote (and (cl-typep ,val ',head)
2952 (cl-typep ,val ',rest))))
2954 (inline-quote (or (cl-typep ,val ',head)
2955 (cl-typep ,val ',rest)))))))))
2956 (`(eql ,v) (inline-quote (and (eql ,val ',v) t)))
2957 (`(member . ,args) (inline-quote (and (memql ,val ',args) t)))
2958 (`(satisfies ,pred) (inline-quote (funcall #',pred ,val)))
2959 ((and (pred symbolp) type (guard (get type 'cl-deftype-handler)))
2960 (inline-quote
2961 (cl-typep ,val ',(funcall (get type 'cl-deftype-handler)))))
2962 ((and (pred symbolp) type (guard (get type 'cl-deftype-satisfies)))
2963 (inline-quote (funcall #',(get type 'cl-deftype-satisfies) ,val)))
2964 ((and (or 'nil 't) type) (inline-quote ',type))
2965 ((and (pred symbolp) type)
2966 (let* ((name (symbol-name type))
2967 (namep (intern (concat name "p"))))
2968 (cond
2969 ((cl--macroexp-fboundp namep) (inline-quote (funcall #',namep ,val)))
2970 ((cl--macroexp-fboundp
2971 (setq namep (intern (concat name "-p"))))
2972 (inline-quote (funcall #',namep ,val)))
2973 ((cl--macroexp-fboundp type) (inline-quote (funcall #',type ,val)))
2974 (t (error "Unknown type %S" type)))))
2975 (type (error "Bad type spec: %s" type)))))
2978 ;;;###autoload
2979 (defmacro cl-check-type (form type &optional string)
2980 "Verify that FORM is of type TYPE; signal an error if not.
2981 STRING is an optional description of the desired type."
2982 (declare (debug (place cl-type-spec &optional stringp)))
2983 (and (or (not (cl--compiling-file))
2984 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
2985 (macroexp-let2 macroexp-copyable-p temp form
2986 `(progn (or (cl-typep ,temp ',type)
2987 (signal 'wrong-type-argument
2988 (list ,(or string `',type) ,temp ',form)))
2989 nil))))
2991 ;;;###autoload
2992 (defmacro cl-assert (form &optional show-args string &rest args)
2993 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
2994 "Verify that FORM returns non-nil; signal an error if not.
2995 Second arg SHOW-ARGS means to include arguments of FORM in message.
2996 Other args STRING and ARGS... are arguments to be passed to `error'.
2997 They are not evaluated unless the assertion fails. If STRING is
2998 omitted, a default message listing FORM itself is used."
2999 (declare (debug (form &rest form)))
3000 (and (or (not (cl--compiling-file))
3001 (< cl--optimize-speed 3) (= cl--optimize-safety 3))
3002 (let ((sargs (and show-args
3003 (delq nil (mapcar (lambda (x)
3004 (unless (macroexp-const-p x)
3006 (cdr form))))))
3007 `(progn
3008 (or ,form
3009 (cl--assertion-failed
3010 ',form ,@(if (or string sargs args)
3011 `(,string (list ,@sargs) (list ,@args)))))
3012 nil))))
3014 ;;; Compiler macros.
3016 ;;;###autoload
3017 (defmacro cl-define-compiler-macro (func args &rest body)
3018 "Define a compiler-only macro.
3019 This is like `defmacro', but macro expansion occurs only if the call to
3020 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
3021 for optimizing the way calls to FUNC are compiled; the form returned by
3022 BODY should do the same thing as a call to the normal function called
3023 FUNC, though possibly more efficiently. Note that, like regular macros,
3024 compiler macros are expanded repeatedly until no further expansions are
3025 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
3026 original function call alone by declaring an initial `&whole foo' parameter
3027 and then returning foo."
3028 (declare (debug cl-defmacro) (indent 2))
3029 (let ((p args) (res nil))
3030 (while (consp p) (push (pop p) res))
3031 (setq args (nconc (nreverse res) (and p (list '&rest p)))))
3032 ;; FIXME: The code in bytecomp mishandles top-level expressions that define
3033 ;; uninterned functions. E.g. it would generate code like:
3034 ;; (defalias '#1=#:foo--cmacro #[514 ...])
3035 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
3036 ;; So we circumvent this by using an interned name.
3037 (let ((fname (intern (concat (symbol-name func) "--cmacro"))))
3038 `(eval-and-compile
3039 ;; Name the compiler-macro function, so that `symbol-file' can find it.
3040 (cl-defun ,fname ,(if (memq '&whole args) (delq '&whole args)
3041 (cons '_cl-whole-arg args))
3042 ,@body)
3043 (put ',func 'compiler-macro #',fname))))
3045 ;;;###autoload
3046 (defun cl-compiler-macroexpand (form)
3047 "Like `macroexpand', but for compiler macros.
3048 Expands FORM repeatedly until no further expansion is possible.
3049 Returns FORM unchanged if it has no compiler macro, or if it has a
3050 macro that returns its `&whole' argument."
3051 (while
3052 (let ((func (car-safe form)) (handler nil))
3053 (while (and (symbolp func)
3054 (not (setq handler (get func 'compiler-macro)))
3055 (fboundp func)
3056 (or (not (autoloadp (symbol-function func)))
3057 (autoload-do-load (symbol-function func) func)))
3058 (setq func (symbol-function func)))
3059 (and handler
3060 (not (eq form (setq form (apply handler form (cdr form))))))))
3061 form)
3063 ;; Optimize away unused block-wrappers.
3065 (defvar cl--active-block-names nil)
3067 (cl-define-compiler-macro cl--block-wrapper (cl-form)
3068 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
3069 (cl--active-block-names (cons cl-entry cl--active-block-names))
3070 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
3071 (macroexp-progn (cddr cl-form))
3072 macroexpand-all-environment)))
3073 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
3074 ;; to indicate that this return value is already fully expanded.
3075 (if (cdr cl-entry)
3076 `(catch ,(nth 1 cl-form) ,@(macroexp-unprogn cl-body))
3077 cl-body)))
3079 (cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
3080 (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
3081 (if cl-found (setcdr cl-found t)))
3082 `(throw ,cl-tag ,cl-value))
3084 ;; Compile-time optimizations for some functions defined in this package.
3086 (defun cl--compiler-macro-member (form a list &rest keys)
3087 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3088 (cl--const-expr-val (nth 1 keys)))))
3089 (cond ((eq test 'eq) `(memq ,a ,list))
3090 ((eq test 'equal) `(member ,a ,list))
3091 ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
3092 (t form))))
3094 (defun cl--compiler-macro-assoc (form a list &rest keys)
3095 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3096 (cl--const-expr-val (nth 1 keys)))))
3097 (cond ((eq test 'eq) `(assq ,a ,list))
3098 ((eq test 'equal) `(assoc ,a ,list))
3099 ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
3100 (if (floatp (cl--const-expr-val a))
3101 `(assoc ,a ,list) `(assq ,a ,list)))
3102 (t form))))
3104 ;;;###autoload
3105 (defun cl--compiler-macro-adjoin (form a list &rest keys)
3106 (if (memq :key keys) form
3107 (macroexp-let2* macroexp-copyable-p ((va a) (vlist list))
3108 `(if (cl-member ,va ,vlist ,@keys) ,vlist (cons ,va ,vlist)))))
3110 (defun cl--compiler-macro-get (_form sym prop &optional def)
3111 (if def
3112 `(cl-getf (symbol-plist ,sym) ,prop ,def)
3113 `(get ,sym ,prop)))
3115 (dolist (y '(cl-first cl-second cl-third cl-fourth
3116 cl-fifth cl-sixth cl-seventh
3117 cl-eighth cl-ninth cl-tenth
3118 cl-rest cl-endp cl-plusp cl-minusp
3119 cl-caaar cl-caadr cl-cadar
3120 cl-caddr cl-cdaar cl-cdadr
3121 cl-cddar cl-cdddr cl-caaaar
3122 cl-caaadr cl-caadar cl-caaddr
3123 cl-cadaar cl-cadadr cl-caddar
3124 cl-cadddr cl-cdaaar cl-cdaadr
3125 cl-cdadar cl-cdaddr cl-cddaar
3126 cl-cddadr cl-cdddar cl-cddddr))
3127 (put y 'side-effect-free t))
3129 ;;; Things that are inline.
3130 (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
3131 cl-notevery cl-revappend cl-nreconc gethash))
3133 ;;; Things that are side-effect-free.
3134 (mapc (lambda (x) (function-put x 'side-effect-free t))
3135 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
3136 cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
3137 cl-subseq cl-list-length cl-get cl-getf))
3139 ;;; Things that are side-effect-and-error-free.
3140 (mapc (lambda (x) (function-put x 'side-effect-free 'error-free))
3141 '(eql cl-list* cl-subst cl-acons cl-equalp
3142 cl-random-state-p copy-tree cl-sublis))
3144 ;;; Types and assertions.
3146 ;;;###autoload
3147 (defmacro cl-deftype (name arglist &rest body)
3148 "Define NAME as a new data type.
3149 The type name can then be used in `cl-typecase', `cl-check-type', etc."
3150 (declare (debug cl-defmacro) (doc-string 3) (indent 2))
3151 `(cl-eval-when (compile load eval)
3152 (put ',name 'cl-deftype-handler
3153 (cl-function (lambda (&cl-defs ('*) ,@arglist) ,@body)))))
3155 (cl-deftype extended-char () `(and character (not base-char)))
3157 ;;; Additional functions that we can now define because we've defined
3158 ;;; `cl-defsubst' and `cl-typep'.
3160 (define-inline cl-struct-slot-value (struct-type slot-name inst)
3161 "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
3162 STRUCT and SLOT-NAME are symbols. INST is a structure instance."
3163 (declare (side-effect-free t))
3164 (inline-letevals (struct-type slot-name inst)
3165 (inline-quote
3166 (progn
3167 (unless (cl-typep ,inst ,struct-type)
3168 (signal 'wrong-type-argument (list ,struct-type ,inst)))
3169 ;; We could use `elt', but since the byte compiler will resolve the
3170 ;; branch below at compile time, it's more efficient to use the
3171 ;; type-specific accessor.
3172 (if (eq (cl-struct-sequence-type ,struct-type) 'list)
3173 (nth (cl-struct-slot-offset ,struct-type ,slot-name) ,inst)
3174 (aref ,inst (cl-struct-slot-offset ,struct-type ,slot-name)))))))
3176 (run-hooks 'cl-macs-load-hook)
3178 ;; Local variables:
3179 ;; byte-compile-dynamic: t
3180 ;; generated-autoload-file: "cl-loaddefs.el"
3181 ;; End:
3183 (provide 'cl-macs)
3185 ;;; cl-macs.el ends here