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