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