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