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