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