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