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