1 ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993, 2001-2018 Free Software Foundation, Inc.
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
7 ;; Keywords: extensions
10 ;; This file is part of GNU Emacs.
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.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;; These are extensions to Emacs Lisp that provide a degree of
28 ;; Common Lisp compatibility, beyond what is already built-in
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.
34 ;; Bug reports, comments, and suggestions are welcome!
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.
41 ;; See cl.el for Change Log.
48 ;; `gv' is required here because cl-macs can be loaded before loaddefs.el.
51 (defmacro cl--pop2
(place)
52 (declare (debug edebug-sexps
))
53 `(prog1 (car (cdr ,place
))
54 (setq ,place
(cdr (cdr ,place
)))))
56 (defvar cl--optimize-safety
)
57 (defvar cl--optimize-speed
)
61 ;; Place compiler macros at the beginning, otherwise uses of the corresponding
62 ;; functions can lead to recursive-loads that prevent the calls from
66 (defun cl--compiler-macro-list* (_form arg
&rest others
)
67 (let* ((args (reverse (cons arg others
)))
69 (while (setq args
(cdr args
))
70 (setq form
`(cons ,(car args
) ,form
)))
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.
77 (define-obsolete-function-alias 'cl--compiler-macro-cXXr
78 'internal--compiler-macro-cXXr
"25.1")
80 ;;; Some predicates for analyzing Lisp forms.
81 ;; These are used by various
82 ;; macro expanders to optimize the results in certain common cases.
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
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
))
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
))))
103 (defun cl--simple-exprs-p (xs)
104 (while (and xs
(cl--simple-expr-p (car xs
)))
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
))
116 (while (and (setq x
(cdr x
)) (cl--safe-expr-p (car x
))))
119 ;;; Check if constant (i.e., no side effects or dependencies).
120 (defun cl--const-expr-p (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
))
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
))))
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
))))
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
)))
153 (defun cl--expr-contains-any (x y
)
154 (while (and y
(not (cl--expr-contains x
(car y
)))) (pop y
))
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
))))
164 (defvar cl--gensym-counter
0)
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
))))
175 (defvar cl--gentemp-counter
0)
177 (defun cl-gentemp (&optional prefix
)
178 "Generate a new interned symbol with a unique name.
179 The name is made by appending a number to PREFIX, default \"T\"."
180 (let ((pfix (if (stringp prefix
) prefix
"T"))
182 (while (intern-soft (setq name
(format "%s%d" pfix cl--gentemp-counter
)))
183 (setq cl--gentemp-counter
(1+ cl--gentemp-counter
)))
187 ;;; Program structure.
189 (def-edebug-spec cl-declarations
190 (&rest
("cl-declare" &rest sexp
)))
192 (def-edebug-spec cl-declarations-or-string
193 (&or lambda-doc cl-declarations
))
195 (def-edebug-spec cl-lambda-list
196 (([&rest cl-lambda-arg
]
197 [&optional
["&optional" cl-
&optional-arg
&rest cl-
&optional-arg
]]
198 [&optional
["&rest" cl-lambda-arg
]]
199 [&optional
["&key" [cl-
&key-arg
&rest cl-
&key-arg
]
200 &optional
"&allow-other-keys"]]
201 [&optional
["&aux" &rest
202 &or
(symbolp &optional def-form
) symbolp
]]
205 (def-edebug-spec cl-
&optional-arg
206 (&or
(cl-lambda-arg &optional def-form arg
) arg
))
208 (def-edebug-spec cl-
&key-arg
209 (&or
([&or
(symbolp cl-lambda-arg
) arg
] &optional def-form arg
) arg
))
211 (def-edebug-spec cl-lambda-arg
212 (&or arg cl-lambda-list1
))
214 (def-edebug-spec cl-lambda-list1
215 (([&optional
["&whole" arg
]] ;; only allowed at lower levels
216 [&rest cl-lambda-arg
]
217 [&optional
["&optional" cl-
&optional-arg
&rest cl-
&optional-arg
]]
218 [&optional
["&rest" cl-lambda-arg
]]
219 [&optional
["&key" cl-
&key-arg
&rest cl-
&key-arg
220 &optional
"&allow-other-keys"]]
221 [&optional
["&aux" &rest
222 &or
(symbolp &optional def-form
) symbolp
]]
225 (def-edebug-spec cl-type-spec sexp
)
227 (defconst cl--lambda-list-keywords
228 '(&optional
&rest
&key
&allow-other-keys
&aux
&whole
&body
&environment
))
230 ;; Internal hacks used in formal arg lists:
231 ;; - &cl-quote: Added to formal-arglists to mean that any default value
232 ;; mentioned in the formal arglist should be considered as implicitly
233 ;; quoted rather than evaluated. This is used in `cl-defsubst' when
234 ;; performing compiler-macro-expansion, since at that time the
235 ;; arguments hold expressions rather than values.
236 ;; - &cl-defs (DEF . DEFS): Gives the default value to use for missing
237 ;; optional arguments which don't have an explicit default value.
238 ;; DEFS is an alist mapping vars to their default default value.
239 ;; and DEF is the default default to use for all other vars.
241 (defvar cl--bind-block
) ;Name of surrounding block, only use for `signal' data.
242 (defvar cl--bind-defs
) ;(DEF . DEFS) giving the "default default" for optargs.
243 (defvar cl--bind-enquote
) ;Non-nil if &cl-quote was in the formal arglist!
244 (defvar cl--bind-lets
) (defvar cl--bind-forms
)
246 (defun cl--transform-lambda (form bind-block
)
247 "Transform a function form FORM of name BIND-BLOCK.
248 BIND-BLOCK is the name of the symbol to which the function will be bound,
249 and which will be used for the name of the `cl-block' surrounding the
251 FORM is of the form (ARGS . BODY)."
252 (let* ((args (car form
)) (body (cdr form
)) (orig-args args
)
253 (cl--bind-block bind-block
) (cl--bind-defs nil
) (cl--bind-enquote nil
)
254 (parsed-body (macroexp-parse-body body
))
255 (header (car parsed-body
)) (simple-args nil
))
256 (setq body
(cdr parsed-body
))
257 ;; "(. X) to (&rest X)" conversion already done in cl--do-arglist, but we
258 ;; do it here as well, so as to be able to see if we can avoid
260 (setq args
(if (listp args
) (cl-copy-list args
) (list '&rest args
)))
261 (let ((p (last args
))) (if (cdr p
) (setcdr p
(list '&rest
(cdr p
)))))
262 (let ((cl-defs (memq '&cl-defs args
)))
264 (setq cl--bind-defs
(cadr cl-defs
))
265 ;; Remove "&cl-defs DEFS" from args.
266 (setcdr cl-defs
(cddr cl-defs
))
267 (setq args
(delq '&cl-defs args
))))
268 (if (setq cl--bind-enquote
(memq '&cl-quote args
))
269 (setq args
(delq '&cl-quote args
)))
270 (if (memq '&whole args
) (error "&whole not currently implemented"))
271 (let* ((p (memq '&environment args
))
273 (if p
(setq args
(nconc (delq (car p
) (delq v args
))
274 `(&aux
(,v macroexpand-all-environment
))))))
275 ;; Take away all the simple args whose parsing can be handled more
276 ;; efficiently by a plain old `lambda' than the manual parsing generated
277 ;; by `cl--do-arglist'.
278 (let ((optional nil
))
279 (while (and args
(symbolp (car args
))
280 (not (memq (car args
) '(nil &rest
&body
&key
&aux
)))
282 ;; Optional args whose default is nil are simple.
283 (null (nth 1 (assq (car args
) (cdr cl--bind-defs
)))))
284 (not (and (eq (car args
) '&optional
) (setq optional t
)
285 (car cl--bind-defs
))))
286 (push (pop args
) simple-args
))
288 (if args
(push '&optional args
))
289 ;; Don't keep a dummy trailing &optional without actual optional args.
290 (if (eq '&optional
(car simple-args
)) (pop simple-args
))))
291 (or (eq cl--bind-block
'cl-none
)
292 (setq body
(list `(cl-block ,cl--bind-block
,@body
))))
293 (let* ((cl--bind-lets nil
) (cl--bind-forms nil
)
297 ((eq (car args
) '&aux
)
299 (setq cl--bind-lets
(nreverse cl--bind-lets
))
301 (t ;; `simple-args' doesn't handle all the parsing that we need,
302 ;; so we pass the rest to cl--do-arglist which will do
304 (let ((slen (length simple-args
)))
305 (when (memq '&optional simple-args
)
308 ;; Macro expansion can take place in the middle of
309 ;; apparently harmless computation, so it should not
310 ;; touch the match-data.
312 (cons (help-add-fundoc-usage
313 (if (stringp (car header
)) (pop header
))
314 ;; Be careful with make-symbol and (back)quote,
316 (help--docstring-quote
317 (let ((print-gensym nil
) (print-quoted t
)
318 (print-escape-newlines t
))
319 (format "%S" (cons 'fn
(cl--make-usage-args
322 ;; FIXME: we'd want to choose an arg name for the &rest param
323 ;; and pass that as `expr' to cl--do-arglist, but that ends up
324 ;; generating code with a redundant let-binding, so we instead
325 ;; pass a dummy and then look in cl--bind-lets to find what var
326 ;; this was bound to.
327 (cl--do-arglist args
:dummy slen
)
328 (setq cl--bind-lets
(nreverse cl--bind-lets
))
329 ;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
330 (list '&rest
(car (pop cl--bind-lets
))))))))
332 (,@(nreverse simple-args
) ,@rest-args
)
334 ,(macroexp-let* cl--bind-lets
336 `(,@(nreverse cl--bind-forms
)
340 (defmacro cl-defun
(name args
&rest body
)
341 "Define NAME as a function.
342 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
343 and BODY is implicitly surrounded by (cl-block NAME ...).
345 The full form of a Common Lisp function argument list is
348 [&optional (VAR [INITFORM [SVAR]])...]
350 [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
351 [&aux (VAR [INITFORM])...])
353 VAR may be replaced recursively with an argument list for
354 destructuring, `&whole' is supported within these sublists. If
355 SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
356 written simply `VAR'. See the Info node `(cl)Argument Lists' for
359 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
361 ;; Same as defun but use cl-lambda-list.
362 (&define
[&or name
("setf" :name setf name
)]
364 cl-declarations-or-string
365 [&optional
("interactive" interactive
)]
369 (let* ((res (cl--transform-lambda (cons args body
) name
))
370 (form `(defun ,name
,@(cdr res
))))
371 (if (car res
) `(progn ,(car res
) ,form
) form
)))
374 (defmacro cl-iter-defun
(name args
&rest body
)
375 "Define NAME as a generator function.
376 Like normal `iter-defun', except ARGLIST allows full Common Lisp conventions,
377 and BODY is implicitly surrounded by (cl-block NAME ...).
379 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
381 ;; Same as iter-defun but use cl-lambda-list.
382 (&define
[&or name
("setf" :name setf name
)]
384 cl-declarations-or-string
385 [&optional
("interactive" interactive
)]
390 (let* ((res (cl--transform-lambda (cons args body
) name
))
391 (form `(iter-defun ,name
,@(cdr res
))))
392 (if (car res
) `(progn ,(car res
) ,form
) form
)))
394 ;; The lambda list for macros is different from that of normal lambdas.
395 ;; Note that &environment is only allowed as first or last items in the
398 (def-edebug-spec cl-macro-list
399 (([&optional
"&environment" arg
]
401 [&optional
["&optional" &rest
402 &or
(cl-macro-arg &optional def-form cl-macro-arg
) arg
]]
403 [&optional
[[&or
"&rest" "&body"] cl-macro-arg
]]
404 [&optional
["&key" [&rest
405 [&or
([&or
(symbolp cl-macro-arg
) arg
]
406 &optional def-form cl-macro-arg
)
408 &optional
"&allow-other-keys"]]
409 [&optional
["&aux" &rest
410 &or
(symbolp &optional def-form
) symbolp
]]
411 [&optional
"&environment" arg
]
414 (def-edebug-spec cl-macro-arg
415 (&or arg cl-macro-list1
))
417 (def-edebug-spec cl-macro-list1
418 (([&optional
"&whole" arg
] ;; only allowed at lower levels
420 [&optional
["&optional" &rest
421 &or
(cl-macro-arg &optional def-form cl-macro-arg
) arg
]]
422 [&optional
[[&or
"&rest" "&body"] cl-macro-arg
]]
423 [&optional
["&key" [&rest
424 [&or
([&or
(symbolp cl-macro-arg
) arg
]
425 &optional def-form cl-macro-arg
)
427 &optional
"&allow-other-keys"]]
428 [&optional
["&aux" &rest
429 &or
(symbolp &optional def-form
) symbolp
]]
433 (defmacro cl-defmacro
(name args
&rest body
)
434 "Define NAME as a macro.
435 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
436 and BODY is implicitly surrounded by (cl-block NAME ...).
438 The full form of a Common Lisp macro argument list is
441 [&optional (VAR [INITFORM [SVAR]])...]
443 [&key (([KEYWORD] VAR) [INITFORM [SVAR]])... [&allow-other-keys]]
444 [&aux (VAR [INITFORM])...]
447 VAR may be replaced recursively with an argument list for
448 destructuring, `&whole' is supported within these sublists. If
449 SVAR, INITFORM, and KEYWORD are all omitted, then `(VAR)' may be
450 written simply `VAR'. See the Info node `(cl)Argument Lists' for
453 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
455 (&define name cl-macro-list cl-declarations-or-string def-body
))
458 (let* ((res (cl--transform-lambda (cons args body
) name
))
459 (form `(defmacro ,name
,@(cdr res
))))
460 (if (car res
) `(progn ,(car res
) ,form
) form
)))
462 (def-edebug-spec cl-lambda-expr
463 (&define
("lambda" cl-lambda-list
464 cl-declarations-or-string
465 [&optional
("interactive" interactive
)]
468 ;; Redefine function-form to also match cl-function
469 (def-edebug-spec function-form
470 ;; form at the end could also handle "function",
471 ;; but recognize it specially to avoid wrapping function forms.
472 (&or
([&or
"quote" "function"] &or symbolp lambda-expr
)
473 ("cl-function" cl-function
)
477 (defmacro cl-function
(func)
478 "Introduce a function.
479 Like normal `function', except that if argument is a lambda form,
480 its argument list allows full Common Lisp conventions."
481 (declare (debug (&or symbolp cl-lambda-expr
)))
482 (if (eq (car-safe func
) 'lambda
)
483 (let* ((res (cl--transform-lambda (cdr func
) 'cl-none
))
484 (form `(function (lambda .
,(cdr res
)))))
485 (if (car res
) `(progn ,(car res
) ,form
) form
))
488 (defun cl--make-usage-var (x)
489 "X can be a var or a (destructuring) lambda-list."
491 ((symbolp x
) (make-symbol (upcase (symbol-name x
))))
492 ((consp x
) (cl--make-usage-args x
))
495 (defun cl--make-usage-args (arglist)
496 (let ((aux (ignore-errors (cl-position '&aux arglist
))))
498 ;; `&aux' args aren't arguments, so let's just drop them from the
500 (setq arglist
(cl-subseq arglist
0 aux
))))
501 (if (cdr-safe (last arglist
)) ;Not a proper list.
502 (let* ((last (last arglist
))
507 (nconc (cl--make-usage-args arglist
) (cl--make-usage-var tail
)))
509 ;; `orig-args' can contain &cl-defs.
510 (let ((x (memq '&cl-defs arglist
)))
511 (when x
(setq arglist
(delq (car x
) (remq (cadr x
) arglist
)))))
516 (let ((first (aref (symbol-name x
) 0)))
519 ;; Strip a leading underscore, since it only
520 ;; means that this argument is unused.
521 (make-symbol (upcase (if (eq ?_ first
)
522 (substring (symbol-name x
) 1)
523 (symbol-name x
)))))))
525 ((memq state
'(nil &rest
)) (cl--make-usage-args x
))
526 (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
528 (if (and (consp (car x
)) (eq state
'&key
))
529 (list (caar x
) (cl--make-usage-var (nth 1 (car x
))))
530 (cl--make-usage-var (car x
)))
532 (cl--make-usage-args (nthcdr 2 x
)) ;SVAR.
536 (defun cl--do-&aux
(args)
537 (while (and (eq (car args
) '&aux
) (pop args
))
538 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
539 (if (consp (car args
))
540 (if (and cl--bind-enquote
(cl-cadar args
))
541 (cl--do-arglist (caar args
)
542 `',(cadr (pop args
)))
543 (cl--do-arglist (caar args
) (cadr (pop args
))))
544 (cl--do-arglist (pop args
) nil
))))
545 (if args
(error "Malformed argument list ends with: %S" args
)))
547 (defun cl--do-arglist (args expr
&optional num
) ; uses cl--bind-*
549 (if (or (memq args cl--lambda-list-keywords
) (not (symbolp args
)))
550 (error "Invalid argument name: %s" args
)
551 (push (list args expr
) cl--bind-lets
))
552 (setq args
(cl-copy-list args
))
553 (let ((p (last args
))) (if (cdr p
) (setcdr p
(list '&rest
(cdr p
)))))
554 (let ((p (memq '&body args
))) (if p
(setcar p
'&rest
)))
555 (if (memq '&environment args
) (error "&environment used incorrectly"))
556 (let ((restarg (memq '&rest args
))
557 (safety (if (cl--compiling-file) cl--optimize-safety
3))
559 (laterarg nil
) (exactarg nil
) minarg
)
560 (or num
(setq num
0))
561 (setq restarg
(if (listp (cadr restarg
))
562 (make-symbol "--cl-rest--")
564 (push (list restarg expr
) cl--bind-lets
)
565 (if (eq (car args
) '&whole
)
566 (push (list (cl--pop2 args
) restarg
) cl--bind-lets
))
568 (setq minarg restarg
)
569 (while (and p
(not (memq (car p
) cl--lambda-list-keywords
)))
570 (or (eq p args
) (setq minarg
(list 'cdr minarg
)))
572 (if (memq (car p
) '(nil &aux
))
573 (setq minarg
`(= (length ,restarg
)
574 ,(length (cl-ldiff args p
)))
575 exactarg
(not (eq args p
)))))
576 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
577 (let ((poparg (list (if (or (cdr args
) (not exactarg
)) 'pop
'car
)
581 (if (or laterarg
(= safety
0)) poparg
583 (signal 'wrong-number-of-arguments
584 (list ,(and (not (eq cl--bind-block
'cl-none
))
586 (length ,restarg
)))))))
587 (setq num
(1+ num
) laterarg t
))
588 (while (and (eq (car args
) '&optional
) (pop args
))
589 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
590 (let ((arg (pop args
)))
591 (or (consp arg
) (setq arg
(list arg
)))
592 (if (cddr arg
) (cl--do-arglist (nth 2 arg
) `(and ,restarg t
)))
593 (let ((def (if (cdr arg
) (nth 1 arg
)
594 (or (car cl--bind-defs
)
595 (nth 1 (assq (car arg
) cl--bind-defs
)))))
596 (poparg `(pop ,restarg
)))
597 (and def cl--bind-enquote
(setq def
`',def
))
598 (cl--do-arglist (car arg
)
599 (if def
`(if ,restarg
,poparg
,def
) poparg
))
600 (setq num
(1+ num
))))))
601 (if (eq (car args
) '&rest
)
602 (let ((arg (cl--pop2 args
)))
603 (if (consp arg
) (cl--do-arglist arg restarg
)))
604 (or (eq (car args
) '&key
) (= safety
0) exactarg
606 (signal 'wrong-number-of-arguments
608 ,(and (not (eq cl--bind-block
'cl-none
))
610 (+ ,num
(length ,restarg
)))))
612 (while (and (eq (car args
) '&key
) (pop args
))
613 (unless (listp keys
) (setq keys nil
))
614 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
615 (let ((arg (pop args
)))
616 (or (consp arg
) (setq arg
(list arg
)))
617 (let* ((karg (if (consp (car arg
)) (caar arg
)
618 (let ((name (symbol-name (car arg
))))
619 ;; Strip a leading underscore, since it only
620 ;; means that this argument is unused, but
621 ;; shouldn't affect the key's name (bug#12367).
622 (if (eq ?_
(aref name
0))
623 (setq name
(substring name
1)))
624 (intern (format ":%s" name
)))))
625 (varg (if (consp (car arg
)) (cl-cadar arg
) (car arg
)))
626 (def (if (cdr arg
) (cadr arg
)
627 ;; The ordering between those two or clauses is
628 ;; irrelevant, since in practice only one of the two
629 ;; is ever non-nil (the car is only used for
630 ;; cl-deftype which doesn't use the cdr).
631 (or (car cl--bind-defs
)
632 (cadr (assq varg cl--bind-defs
)))))
633 (look `(plist-member ,restarg
',karg
)))
634 (and def cl--bind-enquote
(setq def
`',def
))
636 (let* ((temp (or (nth 2 arg
) (make-symbol "--cl-var--")))
637 (val `(car (cdr ,temp
))))
638 (cl--do-arglist temp look
)
641 (prog1 ,val
(setq ,temp t
))
645 `(car (cdr ,(if (null def
)
648 ,(if (eq (cl--const-expr-p def
) t
)
649 `'(nil ,(cl--const-expr-val def
))
650 `(list nil
,def
))))))))
652 (when (consp keys
) (setq keys
(nreverse keys
)))
653 (or (and (eq (car args
) '&allow-other-keys
) (pop args
))
656 ((eq keys t
) nil
) ;No &keys at all
657 ((null keys
) ;A &key but no actual keys specified.
658 (push `(when ,restarg
659 (error ,(format "Keyword argument %%s not one of %s"
664 (let* ((var (make-symbol "--cl-keys--"))
665 (allow '(:allow-other-keys
))
668 ((memq (car ,var
) ',(append keys allow
))
669 (setq ,var
(cdr (cdr ,var
))))
670 ((car (cdr (memq (quote ,@allow
) ,restarg
)))
674 ,(format "Keyword argument %%s not one of %s"
677 (push `(let ((,var
,restarg
)) ,check
) cl--bind-forms
)))))
681 (defun cl--arglist-args (args)
682 (if (nlistp args
) (list args
)
683 (let ((res nil
) (kind nil
) arg
)
685 (setq arg
(pop args
))
686 (if (memq arg cl--lambda-list-keywords
) (setq kind arg
)
687 (if (eq arg
'&cl-defs
) (pop args
)
688 (and (consp arg
) kind
(setq arg
(car arg
)))
689 (and (consp arg
) (cdr arg
) (eq kind
'&key
) (setq arg
(cadr arg
)))
690 (setq res
(nconc res
(cl--arglist-args arg
))))))
691 (nconc res
(and args
(list args
))))))
694 (defmacro cl-destructuring-bind
(args expr
&rest body
)
695 "Bind the variables in ARGS to the result of EXPR and execute BODY."
697 (debug (&define cl-macro-list1 def-form cl-declarations def-body
)))
698 (let* ((cl--bind-lets nil
) (cl--bind-forms nil
)
699 (cl--bind-defs nil
) (cl--bind-block 'cl-none
) (cl--bind-enquote nil
))
700 (cl--do-arglist (or args
'(&aux
)) expr
)
701 (macroexp-let* (nreverse cl--bind-lets
)
702 (macroexp-progn (append (nreverse cl--bind-forms
) body
)))))
705 ;;; The `cl-eval-when' form.
707 (defvar cl--not-toplevel nil
)
710 (defmacro cl-eval-when
(when &rest body
)
711 "Control when BODY is evaluated.
712 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
713 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
714 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
716 \(fn (WHEN...) BODY...)"
717 (declare (indent 1) (debug (sexp body
)))
718 (if (and (fboundp 'cl--compiling-file
) (cl--compiling-file)
719 (not cl--not-toplevel
) (not (boundp 'for-effect
))) ;Horrible kludge.
720 (let ((comp (or (memq 'compile when
) (memq :compile-toplevel when
)))
721 (cl--not-toplevel t
))
722 (if (or (memq 'load when
) (memq :load-toplevel when
))
723 (if comp
(cons 'progn
(mapcar 'cl--compile-time-too body
))
724 `(if nil nil
,@body
))
725 (progn (if comp
(eval (cons 'progn body
))) nil
)))
726 (and (or (memq 'eval when
) (memq :execute when
))
727 (cons 'progn body
))))
729 (defun cl--compile-time-too (form)
730 (or (and (symbolp (car-safe form
)) (get (car-safe form
) 'byte-hunk-handler
))
731 (setq form
(macroexpand
732 form
(cons '(cl-eval-when) byte-compile-macro-environment
))))
733 (cond ((eq (car-safe form
) 'progn
)
734 (cons 'progn
(mapcar 'cl--compile-time-too
(cdr form
))))
735 ((eq (car-safe form
) 'cl-eval-when
)
736 (let ((when (nth 1 form
)))
737 (if (or (memq 'eval when
) (memq :execute when
))
738 `(cl-eval-when (compile ,@when
) ,@(cddr form
))
740 (t (eval form
) form
)))
743 (defmacro cl-load-time-value
(form &optional _read-only
)
744 "Like `progn', but evaluates the body at load time.
745 The result of the body appears to the compiler as a quoted constant."
746 (declare (debug (form &optional sexp
)))
747 (if (cl--compiling-file)
748 (let* ((temp (cl-gentemp "--cl-load-time--"))
749 (set `(setq ,temp
,form
)))
750 (if (and (fboundp 'byte-compile-file-form-defmumble
)
751 (boundp 'this-kind
) (boundp 'that-one
))
752 ;; Else, we can't output right away, so we have to delay it to the
753 ;; next time we're at the top-level.
754 ;; FIXME: Use advice-add/remove.
755 (fset 'byte-compile-file-form
756 (let ((old (symbol-function 'byte-compile-file-form
)))
758 (fset 'byte-compile-file-form old
)
759 (byte-compile-file-form set
)
760 (byte-compile-file-form form
))))
761 ;; If we're not in the middle of compiling something, we can
762 ;; output directly to byte-compile-outbuffer, to make sure
763 ;; temp is set before we use it.
764 (print set byte-compile--outbuffer
))
769 ;;; Conditional control structures.
772 (defmacro cl-case
(expr &rest clauses
)
773 "Eval EXPR and choose among clauses on that value.
774 Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
775 against each key in each KEYLIST; the corresponding BODY is evaluated.
776 If no clause succeeds, cl-case returns nil. A single atom may be used in
777 place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
778 allowed only in the final clause, and matches if no other keys match.
779 Key values are compared by `eql'.
780 \n(fn EXPR (KEYLIST BODY...)...)"
781 (declare (indent 1) (debug (form &rest
(sexp body
))))
782 (macroexp-let2 macroexp-copyable-p temp expr
783 (let* ((head-list nil
))
787 (cons (cond ((memq (car c
) '(t otherwise
)) t
)
788 ((eq (car c
) 'cl--ecase-error-flag
)
789 `(error "cl-ecase failed: %s, %s"
790 ,temp
',(reverse head-list
)))
792 (setq head-list
(append (car c
) head-list
))
793 `(cl-member ,temp
',(car c
)))
795 (if (memq (car c
) head-list
)
796 (error "Duplicate key in case: %s"
798 (push (car c
) head-list
)
799 `(eql ,temp
',(car c
))))
800 (or (cdr c
) '(nil))))
804 (defmacro cl-ecase
(expr &rest clauses
)
805 "Like `cl-case', but error if no case fits.
806 `otherwise'-clauses are not allowed.
807 \n(fn EXPR (KEYLIST BODY...)...)"
808 (declare (indent 1) (debug cl-case
))
809 `(cl-case ,expr
,@clauses
(cl--ecase-error-flag)))
812 (defmacro cl-typecase
(expr &rest clauses
)
813 "Evals EXPR, chooses among clauses on that value.
814 Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
815 satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
816 cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
817 final clause, and matches if no other keys match.
818 \n(fn EXPR (TYPE BODY...)...)"
820 (debug (form &rest
([&or cl-type-spec
"otherwise"] body
))))
821 (macroexp-let2 macroexp-copyable-p temp expr
822 (let* ((type-list nil
))
828 (cons (cond ((eq (car c
) 'otherwise
) t
)
829 ((eq (car c
) 'cl--ecase-error-flag
)
830 `(error "cl-etypecase failed: %s, %s"
831 ,temp
',(reverse type-list
)))
833 (push (car c
) type-list
)
834 `(cl-typep ,temp
',(car c
))))
835 (or (cdr c
) '(nil)))))
839 (defmacro cl-etypecase
(expr &rest clauses
)
840 "Like `cl-typecase', but error if no case fits.
841 `otherwise'-clauses are not allowed.
842 \n(fn EXPR (TYPE BODY...)...)"
843 (declare (indent 1) (debug cl-typecase
))
844 `(cl-typecase ,expr
,@clauses
(cl--ecase-error-flag)))
847 ;;; Blocks and exits.
850 (defmacro cl-block
(name &rest body
)
851 "Define a lexically-scoped block named NAME.
852 NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
853 to jump prematurely out of the block. This differs from `catch' and `throw'
854 in two respects: First, the NAME is an unevaluated symbol rather than a
855 quoted symbol or other form; and second, NAME is lexically rather than
856 dynamically scoped: Only references to it within BODY will work. These
857 references may appear inside macro expansions, but not inside functions
859 (declare (indent 1) (debug (symbolp body
)))
860 (if (cl--safe-expr-p `(progn ,@body
)) `(progn ,@body
)
862 (catch ',(intern (format "--cl-block-%s--" name
))
866 (defmacro cl-return
(&optional result
)
867 "Return from the block named nil.
868 This is equivalent to `(cl-return-from nil RESULT)'."
869 (declare (debug (&optional form
)))
870 `(cl-return-from nil
,result
))
873 (defmacro cl-return-from
(name &optional result
)
874 "Return from the block named NAME.
875 This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
876 returning RESULT from that form (or nil if RESULT is omitted).
877 This is compatible with Common Lisp, but note that `defun' and
878 `defmacro' do not create implicit blocks as they do in Common Lisp."
879 (declare (indent 1) (debug (symbolp &optional form
)))
880 (let ((name2 (intern (format "--cl-block-%s--" name
))))
881 `(cl--block-throw ',name2
,result
)))
884 ;;; The "cl-loop" macro.
886 (defvar cl--loop-args
) (defvar cl--loop-accum-var
) (defvar cl--loop-accum-vars
)
887 (defvar cl--loop-bindings
) (defvar cl--loop-body
)
888 (defvar cl--loop-finally
)
889 (defvar cl--loop-finish-flag
) ;Symbol set to nil to exit the loop?
890 (defvar cl--loop-first-flag
)
891 (defvar cl--loop-initially
) (defvar cl--loop-iterator-function
)
892 (defvar cl--loop-name
)
893 (defvar cl--loop-result
) (defvar cl--loop-result-explicit
)
894 (defvar cl--loop-result-var
) (defvar cl--loop-steps
)
895 (defvar cl--loop-symbol-macs
) (defvar cl--loop-guard-cond
)
897 (defun cl--loop-set-iterator-function (kind iterator
)
898 (if cl--loop-iterator-function
899 ;; FIXME: Of course, we could make it work, but why bother.
900 (error "Iteration on %S does not support this combination" kind
)
901 (setq cl--loop-iterator-function iterator
)))
904 (defmacro cl-loop
(&rest loop-args
)
905 "The Common Lisp `loop' macro.
906 Valid clauses include:
908 for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2 [by EXPR3]
909 for VAR = EXPR1 then EXPR2
910 for VAR in/on/in-ref LIST [by FUNC]
911 for VAR across/across-ref ARRAY
913 the elements of/of-ref SEQUENCE [using (index VAR2)]
914 the symbols [of OBARRAY]
915 the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
916 the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
917 the overlays/intervals [of BUFFER] [from POS1] [to POS2]
919 the windows [of FRAME]
922 while/until/always/never/thereis CONDITION
923 Accumulation clauses:
924 collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
926 Miscellaneous clauses:
928 if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
930 initially/finally [do] EXPRS...
932 [finally] return EXPR
934 For more details, see Info node `(cl)Loop Facility'.
937 (declare (debug (&rest
&or
938 ;; These are usually followed by a symbol, but it can
939 ;; actually be any destructuring-bind pattern, which
940 ;; would erroneously match `form'.
941 [[&or
"for" "as" "with" "and"] sexp
]
942 ;; These are followed by expressions which could
943 ;; erroneously match `symbolp'.
944 [[&or
"from" "upfrom" "downfrom" "to" "upto" "downto"
945 "above" "below" "by" "in" "on" "=" "across"
946 "repeat" "while" "until" "always" "never"
947 "thereis" "collect" "append" "nconc" "sum"
948 "count" "maximize" "minimize" "if" "unless"
951 ["using" (symbolp symbolp
)]
952 ;; Simple default, which covers 99% of the cases.
954 (if (not (memq t
(mapcar #'symbolp
955 (delq nil
(delq t
(cl-copy-list loop-args
))))))
956 `(cl-block nil
(while t
,@loop-args
))
957 (let ((cl--loop-args loop-args
) (cl--loop-name nil
) (cl--loop-bindings nil
)
958 (cl--loop-body nil
) (cl--loop-steps nil
)
959 (cl--loop-result nil
) (cl--loop-result-explicit nil
)
960 (cl--loop-result-var nil
) (cl--loop-finish-flag nil
)
961 (cl--loop-accum-var nil
) (cl--loop-accum-vars nil
)
962 (cl--loop-initially nil
) (cl--loop-finally nil
)
963 (cl--loop-iterator-function nil
) (cl--loop-first-flag nil
)
964 (cl--loop-symbol-macs nil
) (cl--loop-guard-cond nil
))
965 ;; Here is more or less how those dynbind vars are used after looping
966 ;; over cl--parse-loop-clause:
968 ;; (cl-block ,cl--loop-name
969 ;; (cl-symbol-macrolet ,cl--loop-symbol-macs
970 ;; (foldl #'cl--loop-let
971 ;; `((,cl--loop-result-var)
972 ;; ((,cl--loop-first-flag t))
973 ;; ((,cl--loop-finish-flag t))
974 ;; ,@cl--loop-bindings)
975 ;; ,@(nreverse cl--loop-initially)
976 ;; (while ;(well: cl--loop-iterator-function)
977 ;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
978 ;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
979 ;; ,@(nreverse cl--loop-steps)
980 ;; (setq ,cl--loop-first-flag nil))
981 ;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
982 ;; ,cl--loop-result-var
983 ;; ,@(nreverse cl--loop-finally)
984 ;; ,(or cl--loop-result-explicit
985 ;; cl--loop-result)))))
987 (setq cl--loop-args
(append cl--loop-args
'(cl-end-loop)))
988 (while (not (eq (car cl--loop-args
) 'cl-end-loop
))
989 (cl--parse-loop-clause))
990 (if cl--loop-finish-flag
991 (push `((,cl--loop-finish-flag t
)) cl--loop-bindings
))
992 (if cl--loop-first-flag
993 (progn (push `((,cl--loop-first-flag t
)) cl--loop-bindings
)
994 (push `(setq ,cl--loop-first-flag nil
) cl--loop-steps
)))
995 (let* ((epilogue (nconc (nreverse cl--loop-finally
)
996 (list (or cl--loop-result-explicit
998 (ands (cl--loop-build-ands (nreverse cl--loop-body
)))
1002 (if (or (not cl--loop-guard-cond
) (not cl--loop-first-flag
))
1003 (nreverse cl--loop-steps
)
1004 ;; Right after update the loop variable ensure that the loop
1005 ;; condition, i.e. (car ands), is still satisfied; otherwise,
1006 ;; set `cl--loop-first-flag' nil and skip the remaining
1007 ;; body forms (#Bug#29799).
1009 ;; (last cl--loop-steps) updates the loop var
1010 ;; (car (butlast cl--loop-steps)) sets `cl--loop-first-flag' nil
1011 ;; (nreverse (cdr (butlast cl--loop-steps))) are the
1012 ;; remaining body forms.
1013 (append (last cl--loop-steps
)
1015 ,@(nreverse (cdr (butlast cl--loop-steps
)))))
1016 `(,(car (butlast cl--loop-steps
)))))))
1018 (nreverse cl--loop-initially
)
1019 (list (if cl--loop-iterator-function
1020 `(cl-block --cl-finish--
1021 ,(funcall cl--loop-iterator-function
1022 (if (eq (car ands
) t
) while-body
1023 (cons `(or ,(car ands
)
1028 `(while ,(car ands
) ,@while-body
)))
1029 (if cl--loop-finish-flag
1030 (if (equal epilogue
'(nil)) (list cl--loop-result-var
)
1031 `((if ,cl--loop-finish-flag
1032 (progn ,@epilogue
) ,cl--loop-result-var
)))
1034 (if cl--loop-result-var
1035 (push (list cl--loop-result-var
) cl--loop-bindings
))
1036 (while cl--loop-bindings
1037 (if (cdar cl--loop-bindings
)
1038 (setq body
(list (cl--loop-let (pop cl--loop-bindings
) body t
)))
1040 (while (and cl--loop-bindings
1041 (not (cdar cl--loop-bindings
)))
1042 (push (car (pop cl--loop-bindings
)) lets
))
1043 (setq body
(list (cl--loop-let lets body nil
))))))
1044 (if cl--loop-symbol-macs
1046 (list `(cl-symbol-macrolet ,cl--loop-symbol-macs
,@body
))))
1047 `(cl-block ,cl--loop-name
,@body
)))))
1049 ;; Below is a complete spec for cl-loop, in several parts that correspond
1050 ;; to the syntax given in CLtL2. The specs do more than specify where
1051 ;; the forms are; it also specifies, as much as Edebug allows, all the
1052 ;; syntactically valid cl-loop clauses. The disadvantage of this
1053 ;; completeness is rigidity, but the "for ... being" clause allows
1054 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
1056 ;; (def-edebug-spec cl-loop
1057 ;; ([&optional ["named" symbolp]]
1063 ;; loop-initial-final]
1064 ;; [&rest loop-clause]
1067 ;; (def-edebug-spec loop-with
1070 ;; [&optional ["=" form]]
1071 ;; &rest ["and" loop-var
1073 ;; [&optional ["=" form]]]))
1075 ;; (def-edebug-spec loop-for-as
1076 ;; ([&or "for" "as"] loop-for-as-subclause
1077 ;; &rest ["and" loop-for-as-subclause]))
1079 ;; (def-edebug-spec loop-for-as-subclause
1083 ;; [[&or "in" "on" "in-ref" "across-ref"]
1084 ;; form &optional ["by" function-form]]
1086 ;; ["=" form &optional ["then" form]]
1089 ;; [&or "the" "each"]
1091 ;; [[&or "element" "elements"]
1092 ;; [&or "of" "in" "of-ref"] form
1093 ;; &optional "using" ["index" symbolp]];; is this right?
1094 ;; [[&or "hash-key" "hash-keys"
1095 ;; "hash-value" "hash-values"]
1097 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
1098 ;; "hash-key" "hash-keys"] sexp)]]
1100 ;; [[&or "symbol" "present-symbol" "external-symbol"
1101 ;; "symbols" "present-symbols" "external-symbols"]
1102 ;; [&or "in" "of"] package-p]
1104 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
1105 ;; [[&or "frame" "frames"
1106 ;; "screen" "screens"
1107 ;; "buffer" "buffers"]]
1109 ;; [[&or "window" "windows"]
1110 ;; [&or "of" "in"] form]
1112 ;; [[&or "overlay" "overlays"
1113 ;; "extent" "extents"]
1114 ;; [&or "of" "in"] form
1115 ;; &optional [[&or "from" "to"] form]]
1117 ;; [[&or "interval" "intervals"]
1118 ;; [&or "in" "of"] form
1119 ;; &optional [[&or "from" "to"] form]
1120 ;; ["property" form]]
1122 ;; [[&or "key-code" "key-codes"
1123 ;; "key-seq" "key-seqs"
1124 ;; "key-binding" "key-bindings"]
1125 ;; [&or "in" "of"] form
1126 ;; &optional ["using" ([&or "key-code" "key-codes"
1127 ;; "key-seq" "key-seqs"
1128 ;; "key-binding" "key-bindings"]
1130 ;; ;; For arbitrary extensions, recognize anything else.
1131 ;; [symbolp &rest &or symbolp form]
1134 ;; ;; arithmetic - must be last since all parts are optional.
1135 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
1136 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
1137 ;; [&optional ["by" form]]
1140 ;; (def-edebug-spec loop-initial-final
1141 ;; (&or ["initially"
1142 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
1143 ;; &rest loop-non-atomic-expr]
1145 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
1146 ;; ["return" form]]))
1148 ;; (def-edebug-spec loop-and-clause
1149 ;; (loop-clause &rest ["and" loop-clause]))
1151 ;; (def-edebug-spec loop-clause
1153 ;; [[&or "while" "until" "always" "never" "thereis"] form]
1155 ;; [[&or "collect" "collecting"
1156 ;; "append" "appending"
1157 ;; "nconc" "nconcing"
1158 ;; "concat" "vconcat"] form
1159 ;; [&optional ["into" loop-var]]]
1161 ;; [[&or "count" "counting"
1163 ;; "maximize" "maximizing"
1164 ;; "minimize" "minimizing"] form
1165 ;; [&optional ["into" loop-var]]
1168 ;; [[&or "if" "when" "unless"]
1169 ;; form loop-and-clause
1170 ;; [&optional ["else" loop-and-clause]]
1171 ;; [&optional "end"]]
1173 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
1176 ;; loop-initial-final
1179 ;; (def-edebug-spec loop-non-atomic-expr
1180 ;; ([¬ atom] form))
1182 ;; (def-edebug-spec loop-var
1183 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
1185 ;; ;; (loop-var . [&or nil loop-var])
1186 ;; ;; (symbolp . [&or nil loop-var])
1187 ;; ;; (symbolp . loop-var)
1188 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
1189 ;; ;; (symbolp . (symbolp . loop-var))
1190 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
1191 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
1193 ;; (def-edebug-spec loop-type-spec
1194 ;; (&optional ["of-type" loop-d-type-spec]))
1196 ;; (def-edebug-spec loop-d-type-spec
1197 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
1201 (defun cl--parse-loop-clause () ; uses loop-*
1202 (let ((word (pop cl--loop-args
))
1203 (hash-types '(hash-key hash-keys hash-value hash-values
))
1204 (key-types '(key-code key-codes key-seq key-seqs
1205 key-binding key-bindings
)))
1208 ((null cl--loop-args
)
1209 (error "Malformed `cl-loop' macro"))
1212 (setq cl--loop-name
(pop cl--loop-args
)))
1214 ((eq word
'initially
)
1215 (if (memq (car cl--loop-args
) '(do doing
)) (pop cl--loop-args
))
1216 (or (consp (car cl--loop-args
))
1217 (error "Syntax error on `initially' clause"))
1218 (while (consp (car cl--loop-args
))
1219 (push (pop cl--loop-args
) cl--loop-initially
)))
1222 (if (eq (car cl--loop-args
) 'return
)
1223 (setq cl--loop-result-explicit
1224 (or (cl--pop2 cl--loop-args
) '(quote nil
)))
1225 (if (memq (car cl--loop-args
) '(do doing
)) (pop cl--loop-args
))
1226 (or (consp (car cl--loop-args
))
1227 (error "Syntax error on `finally' clause"))
1228 (if (and (eq (caar cl--loop-args
) 'return
) (null cl--loop-name
))
1229 (setq cl--loop-result-explicit
1230 (or (nth 1 (pop cl--loop-args
)) '(quote nil
)))
1231 (while (consp (car cl--loop-args
))
1232 (push (pop cl--loop-args
) cl--loop-finally
)))))
1234 ((memq word
'(for as
))
1235 (let ((loop-for-bindings nil
) (loop-for-sets nil
) (loop-for-steps nil
)
1238 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1239 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
1240 ;; these vars get added to the macro-environment.
1241 (let ((var (or (pop cl--loop-args
) (cl-gensym "--cl-var--"))))
1242 (setq word
(pop cl--loop-args
))
1243 (if (eq word
'being
) (setq word
(pop cl--loop-args
)))
1244 (if (memq word
'(the each
)) (setq word
(pop cl--loop-args
)))
1245 (if (memq word
'(buffer buffers
))
1247 cl--loop-args
(cons '(buffer-list) cl--loop-args
)))
1250 ((memq word
'(from downfrom upfrom to downto upto
1252 (push word cl--loop-args
)
1253 (if (memq (car cl--loop-args
) '(downto above
))
1254 (error "Must specify `from' value for downward cl-loop"))
1255 (let* ((down (or (eq (car cl--loop-args
) 'downfrom
)
1256 (memq (nth 2 cl--loop-args
)
1258 (excl (or (memq (car cl--loop-args
) '(above below
))
1259 (memq (nth 2 cl--loop-args
)
1261 (start (and (memq (car cl--loop-args
)
1262 '(from upfrom downfrom
))
1263 (cl--pop2 cl--loop-args
)))
1264 (end (and (memq (car cl--loop-args
)
1265 '(to upto downto above below
))
1266 (cl--pop2 cl--loop-args
)))
1267 (step (and (eq (car cl--loop-args
) 'by
)
1268 (cl--pop2 cl--loop-args
)))
1269 (end-var (and (not (macroexp-const-p end
))
1270 (make-symbol "--cl-var--")))
1271 (step-var (and (not (macroexp-const-p step
))
1272 (make-symbol "--cl-var--"))))
1273 (and step
(numberp step
) (<= step
0)
1274 (error "Loop `by' value is not positive: %s" step
))
1275 (push (list var
(or start
0)) loop-for-bindings
)
1276 (if end-var
(push (list end-var end
) loop-for-bindings
))
1277 (if step-var
(push (list step-var step
)
1281 (if down
(if excl
'> '>=) (if excl
'< '<=))
1282 var
(or end-var end
))
1284 (push (list var
(list (if down
'-
'+) var
1285 (or step-var step
1)))
1288 ((memq word
'(in in-ref on
))
1289 (let* ((on (eq word
'on
))
1290 (temp (if (and on
(symbolp var
))
1291 var
(make-symbol "--cl-var--"))))
1292 (push (list temp
(pop cl--loop-args
)) loop-for-bindings
)
1293 (push `(consp ,temp
) cl--loop-body
)
1294 (if (eq word
'in-ref
)
1295 (push (list var
`(car ,temp
)) cl--loop-symbol-macs
)
1298 (push (list var nil
) loop-for-bindings
)
1299 (push (list var
(if on temp
`(car ,temp
)))
1302 (if (eq (car cl--loop-args
) 'by
)
1303 (let ((step (cl--pop2 cl--loop-args
)))
1304 (if (and (memq (car-safe step
)
1307 (symbolp (nth 1 step
)))
1308 (list (nth 1 step
) temp
)
1309 `(funcall ,step
,temp
)))
1314 (let* ((start (pop cl--loop-args
))
1315 (then (if (eq (car cl--loop-args
) 'then
)
1316 (cl--pop2 cl--loop-args
) start
)))
1317 (push (list var nil
) loop-for-bindings
)
1318 (if (or ands
(eq (car cl--loop-args
) 'and
))
1321 (if ,(or cl--loop-first-flag
1322 (setq cl--loop-first-flag
1323 (make-symbol "--cl-var--")))
1326 (push (list var then
) loop-for-steps
))
1328 (if (eq start then
) start
1329 `(if ,(or cl--loop-first-flag
1330 (setq cl--loop-first-flag
1331 (make-symbol "--cl-var--")))
1335 ((memq word
'(across across-ref
))
1336 (let ((temp-vec (make-symbol "--cl-vec--"))
1337 (temp-len (make-symbol "--cl-len--"))
1338 (temp-idx (make-symbol "--cl-idx--")))
1339 (push (list temp-vec
(pop cl--loop-args
)) loop-for-bindings
)
1340 (push (list temp-len
`(length ,temp-vec
)) loop-for-bindings
)
1341 (push (list temp-idx -
1) loop-for-bindings
)
1342 (push `(< (setq ,temp-idx
(1+ ,temp-idx
))
1345 (if (eq word
'across-ref
)
1346 (push (list var
`(aref ,temp-vec
,temp-idx
))
1347 cl--loop-symbol-macs
)
1348 (push (list var nil
) loop-for-bindings
)
1349 (push (list var
`(aref ,temp-vec
,temp-idx
))
1352 ((memq word
'(element elements
))
1353 (let ((ref (or (memq (car cl--loop-args
) '(in-ref of-ref
))
1354 (and (not (memq (car cl--loop-args
) '(in of
)))
1355 (error "Expected `of'"))))
1356 (seq (cl--pop2 cl--loop-args
))
1357 (temp-seq (make-symbol "--cl-seq--"))
1358 (temp-len (make-symbol "--cl-len--"))
1360 (if (eq (car cl--loop-args
) 'using
)
1361 (if (and (= (length (cadr cl--loop-args
)) 2)
1362 (eq (cl-caadr cl--loop-args
) 'index
))
1363 (cadr (cl--pop2 cl--loop-args
))
1364 (error "Bad `using' clause"))
1365 (make-symbol "--cl-idx--"))))
1366 (push (list temp-seq seq
) loop-for-bindings
)
1367 (push (list temp-idx
0) loop-for-bindings
)
1370 (push (list temp-len
`(length ,temp-seq
))
1372 (push (list var
`(elt ,temp-seq
,temp-idx
))
1373 cl--loop-symbol-macs
)
1374 (push `(< ,temp-idx
,temp-len
) cl--loop-body
))
1375 ;; Evaluate seq length just if needed, that is, when seq is not a cons.
1376 (push (list temp-len
(or (consp seq
) `(length ,temp-seq
)))
1378 (push (list var nil
) loop-for-bindings
)
1379 (push `(and ,temp-seq
1380 (or (consp ,temp-seq
)
1381 (< ,temp-idx
,temp-len
)))
1383 (push (list var
`(if (consp ,temp-seq
)
1385 (aref ,temp-seq
,temp-idx
)))
1387 (push (list temp-idx
`(1+ ,temp-idx
))
1390 ((memq word hash-types
)
1391 (or (memq (car cl--loop-args
) '(in of
))
1392 (error "Expected `of'"))
1393 (let* ((table (cl--pop2 cl--loop-args
))
1395 (if (eq (car cl--loop-args
) 'using
)
1396 (if (and (= (length (cadr cl--loop-args
)) 2)
1397 (memq (cl-caadr cl--loop-args
) hash-types
)
1398 (not (eq (cl-caadr cl--loop-args
) word
)))
1399 (cadr (cl--pop2 cl--loop-args
))
1400 (error "Bad `using' clause"))
1401 (make-symbol "--cl-var--"))))
1402 (if (memq word
'(hash-value hash-values
))
1403 (setq var
(prog1 other
(setq other var
))))
1404 (cl--loop-set-iterator-function
1405 'hash-tables
(lambda (body)
1406 `(maphash (lambda (,var
,other
) .
,body
)
1409 ((memq word
'(symbol present-symbol external-symbol
1410 symbols present-symbols external-symbols
))
1411 (let ((ob (and (memq (car cl--loop-args
) '(in of
))
1412 (cl--pop2 cl--loop-args
))))
1413 (cl--loop-set-iterator-function
1414 'symbols
(lambda (body)
1415 `(mapatoms (lambda (,var
) .
,body
) ,ob
)))))
1417 ((memq word
'(overlay overlays extent extents
))
1418 (let ((buf nil
) (from nil
) (to nil
))
1419 (while (memq (car cl--loop-args
) '(in of from to
))
1420 (cond ((eq (car cl--loop-args
) 'from
)
1421 (setq from
(cl--pop2 cl--loop-args
)))
1422 ((eq (car cl--loop-args
) 'to
)
1423 (setq to
(cl--pop2 cl--loop-args
)))
1424 (t (setq buf
(cl--pop2 cl--loop-args
)))))
1425 (cl--loop-set-iterator-function
1426 'overlays
(lambda (body)
1428 (lambda (,var
,(make-symbol "--cl-var--"))
1429 (progn .
,body
) nil
)
1432 ((memq word
'(interval intervals
))
1433 (let ((buf nil
) (prop nil
) (from nil
) (to nil
)
1434 (var1 (make-symbol "--cl-var1--"))
1435 (var2 (make-symbol "--cl-var2--")))
1436 (while (memq (car cl--loop-args
) '(in of property from to
))
1437 (cond ((eq (car cl--loop-args
) 'from
)
1438 (setq from
(cl--pop2 cl--loop-args
)))
1439 ((eq (car cl--loop-args
) 'to
)
1440 (setq to
(cl--pop2 cl--loop-args
)))
1441 ((eq (car cl--loop-args
) 'property
)
1442 (setq prop
(cl--pop2 cl--loop-args
)))
1443 (t (setq buf
(cl--pop2 cl--loop-args
)))))
1444 (if (and (consp var
) (symbolp (car var
)) (symbolp (cdr var
)))
1445 (setq var1
(car var
) var2
(cdr var
))
1446 (push (list var
`(cons ,var1
,var2
)) loop-for-sets
))
1447 (cl--loop-set-iterator-function
1448 'intervals
(lambda (body)
1450 (lambda (,var1
,var2
) .
,body
)
1451 ,buf
,prop
,from
,to
)))))
1453 ((memq word key-types
)
1454 (or (memq (car cl--loop-args
) '(in of
))
1455 (error "Expected `of'"))
1456 (let ((cl-map (cl--pop2 cl--loop-args
))
1458 (if (eq (car cl--loop-args
) 'using
)
1459 (if (and (= (length (cadr cl--loop-args
)) 2)
1460 (memq (cl-caadr cl--loop-args
) key-types
)
1461 (not (eq (cl-caadr cl--loop-args
) word
)))
1462 (cadr (cl--pop2 cl--loop-args
))
1463 (error "Bad `using' clause"))
1464 (make-symbol "--cl-var--"))))
1465 (if (memq word
'(key-binding key-bindings
))
1466 (setq var
(prog1 other
(setq other var
))))
1467 (cl--loop-set-iterator-function
1468 'keys
(lambda (body)
1469 `(,(if (memq word
'(key-seq key-seqs
))
1470 'cl--map-keymap-recursively
'map-keymap
)
1471 (lambda (,var
,other
) .
,body
) ,cl-map
)))))
1473 ((memq word
'(frame frames screen screens
))
1474 (let ((temp (make-symbol "--cl-var--")))
1475 (push (list var
'(selected-frame))
1477 (push (list temp nil
) loop-for-bindings
)
1478 (push `(prog1 (not (eq ,var
,temp
))
1479 (or ,temp
(setq ,temp
,var
)))
1481 (push (list var
`(next-frame ,var
))
1484 ((memq word
'(window windows
))
1485 (let ((scr (and (memq (car cl--loop-args
) '(in of
))
1486 (cl--pop2 cl--loop-args
)))
1487 (temp (make-symbol "--cl-var--"))
1488 (minip (make-symbol "--cl-minip--")))
1489 (push (list var
(if scr
1490 `(frame-selected-window ,scr
)
1491 '(selected-window)))
1493 ;; If we started in the minibuffer, we need to
1494 ;; ensure that next-window will bring us back there
1495 ;; at some point. (Bug#7492).
1496 ;; (Consider using walk-windows instead of cl-loop if
1497 ;; you care about such things.)
1498 (push (list minip
`(minibufferp (window-buffer ,var
)))
1500 (push (list temp nil
) loop-for-bindings
)
1501 (push `(prog1 (not (eq ,var
,temp
))
1502 (or ,temp
(setq ,temp
,var
)))
1504 (push (list var
`(next-window ,var
,minip
))
1508 ;; This is an advertised interface: (info "(cl)Other Clauses").
1509 (let ((handler (and (symbolp word
)
1510 (get word
'cl-loop-for-handler
))))
1512 (funcall handler var
)
1513 (error "Expected a `for' preposition, found %s" word
)))))
1514 (eq (car cl--loop-args
) 'and
))
1516 (pop cl--loop-args
))
1517 (if (and ands loop-for-bindings
)
1518 (push (nreverse loop-for-bindings
) cl--loop-bindings
)
1519 (setq cl--loop-bindings
(nconc (mapcar 'list loop-for-bindings
)
1520 cl--loop-bindings
)))
1523 ,(cl--loop-let (nreverse loop-for-sets
) 'setq ands
)
1526 (when loop-for-steps
1527 (setq cl--loop-guard-cond t
)
1528 (push (cons (if ands
'cl-psetq
'setq
)
1529 (apply 'append
(nreverse loop-for-steps
)))
1533 (let ((temp (make-symbol "--cl-var--")))
1534 (push (list (list temp
(pop cl--loop-args
))) cl--loop-bindings
)
1535 (push `(>= (setq ,temp
(1- ,temp
)) 0) cl--loop-body
)))
1537 ((memq word
'(collect collecting
))
1538 (let ((what (pop cl--loop-args
))
1539 (var (cl--loop-handle-accum nil
'nreverse
)))
1540 (if (eq var cl--loop-accum-var
)
1541 (push `(progn (push ,what
,var
) t
) cl--loop-body
)
1543 (setq ,var
(nconc ,var
(list ,what
)))
1547 ((memq word
'(nconc nconcing append appending
))
1548 (let ((what (pop cl--loop-args
))
1549 (var (cl--loop-handle-accum nil
'nreverse
)))
1552 ,(if (eq var cl--loop-accum-var
)
1554 (,(if (memq word
'(nconc nconcing
))
1555 #'nreverse
#'reverse
)
1558 `(,(if (memq word
'(nconc nconcing
))
1564 ((memq word
'(concat concating
))
1565 (let ((what (pop cl--loop-args
))
1566 (var (cl--loop-handle-accum "")))
1567 (push `(progn (cl-callf concat
,var
,what
) t
) cl--loop-body
)))
1569 ((memq word
'(vconcat vconcating
))
1570 (let ((what (pop cl--loop-args
))
1571 (var (cl--loop-handle-accum [])))
1572 (push `(progn (cl-callf vconcat
,var
,what
) t
) cl--loop-body
)))
1574 ((memq word
'(sum summing
))
1575 (let ((what (pop cl--loop-args
))
1576 (var (cl--loop-handle-accum 0)))
1577 (push `(progn (cl-incf ,var
,what
) t
) cl--loop-body
)))
1579 ((memq word
'(count counting
))
1580 (let ((what (pop cl--loop-args
))
1581 (var (cl--loop-handle-accum 0)))
1582 (push `(progn (if ,what
(cl-incf ,var
)) t
) cl--loop-body
)))
1584 ((memq word
'(minimize minimizing maximize maximizing
))
1585 (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
1587 (let* ((var (cl--loop-handle-accum nil
))
1588 (func (intern (substring (symbol-name word
)
1590 `(setq ,var
(if ,var
(,func
,var
,temp
) ,temp
))))
1595 (let ((bindings nil
))
1596 (while (progn (push (list (pop cl--loop-args
)
1597 (and (eq (car cl--loop-args
) '=)
1598 (cl--pop2 cl--loop-args
)))
1600 (eq (car cl--loop-args
) 'and
))
1601 (pop cl--loop-args
))
1602 (push (nreverse bindings
) cl--loop-bindings
)))
1605 (push (pop cl--loop-args
) cl--loop-body
))
1608 (push `(not ,(pop cl--loop-args
)) cl--loop-body
))
1611 (or cl--loop-finish-flag
1612 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1613 (push `(setq ,cl--loop-finish-flag
,(pop cl--loop-args
)) cl--loop-body
)
1614 (setq cl--loop-result t
))
1617 (or cl--loop-finish-flag
1618 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1619 (push `(setq ,cl--loop-finish-flag
(not ,(pop cl--loop-args
)))
1621 (setq cl--loop-result t
))
1624 (or cl--loop-finish-flag
1625 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1626 (or cl--loop-result-var
1627 (setq cl--loop-result-var
(make-symbol "--cl-var--")))
1628 (push `(setq ,cl--loop-finish-flag
1629 (not (setq ,cl--loop-result-var
,(pop cl--loop-args
))))
1632 ((memq word
'(if when unless
))
1633 (let* ((cond (pop cl--loop-args
))
1634 (then (let ((cl--loop-body nil
))
1635 (cl--parse-loop-clause)
1636 (cl--loop-build-ands (nreverse cl--loop-body
))))
1637 (else (let ((cl--loop-body nil
))
1638 (if (eq (car cl--loop-args
) 'else
)
1639 (progn (pop cl--loop-args
) (cl--parse-loop-clause)))
1640 (cl--loop-build-ands (nreverse cl--loop-body
))))
1641 (simple (and (eq (car then
) t
) (eq (car else
) t
))))
1642 (if (eq (car cl--loop-args
) 'end
) (pop cl--loop-args
))
1643 (if (eq word
'unless
) (setq then
(prog1 else
(setq else then
))))
1644 (let ((form (cons (if simple
(cons 'progn
(nth 1 then
)) (nth 2 then
))
1645 (if simple
(nth 1 else
) (list (nth 2 else
))))))
1646 (setq form
(if (cl--expr-contains form
'it
)
1647 `(let ((it ,cond
)) (if it
,@form
))
1648 `(if ,cond
,@form
)))
1649 (push (if simple
`(progn ,form t
) form
) cl--loop-body
))))
1651 ((memq word
'(do doing
))
1653 (or (consp (car cl--loop-args
)) (error "Syntax error on `do' clause"))
1654 (while (consp (car cl--loop-args
)) (push (pop cl--loop-args
) body
))
1655 (push (cons 'progn
(nreverse (cons t body
))) cl--loop-body
)))
1658 (or cl--loop-finish-flag
1659 (setq cl--loop-finish-flag
(make-symbol "--cl-var--")))
1660 (or cl--loop-result-var
1661 (setq cl--loop-result-var
(make-symbol "--cl-var--")))
1662 (push `(setq ,cl--loop-result-var
,(pop cl--loop-args
)
1663 ,cl--loop-finish-flag nil
)
1667 ;; This is an advertised interface: (info "(cl)Other Clauses").
1668 (let ((handler (and (symbolp word
) (get word
'cl-loop-handler
))))
1669 (or handler
(error "Expected a cl-loop keyword, found %s" word
))
1670 (funcall handler
))))
1671 (if (eq (car cl--loop-args
) 'and
)
1672 (progn (pop cl--loop-args
) (cl--parse-loop-clause)))))
1674 (defun cl--unused-var-p (sym)
1675 (or (null sym
) (eq ?_
(aref (symbol-name sym
) 0))))
1677 (defun cl--loop-let (specs body par
) ; modifies cl--loop-bindings
1678 "Build an expression equivalent to (let SPECS BODY).
1679 SPECS can include bindings using `cl-loop's destructuring (not to be
1680 confused with the patterns of `cl-destructuring-bind').
1681 If PAR is nil, do the bindings step by step, like `let*'.
1682 If BODY is `setq', then use SPECS for assignments rather than for bindings."
1683 (let ((temps nil
) (new nil
))
1686 (while (and p
(or (symbolp (car-safe (car p
))) (null (cl-cadar p
))))
1690 (dolist (spec specs
)
1691 (or (macroexp-const-p (cadr spec
))
1692 (let ((temp (make-symbol "--cl-var--")))
1693 (push (list temp
(cadr spec
)) temps
)
1694 (setcar (cdr spec
) temp
)))))))
1696 (let* ((binding (pop specs
))
1697 (spec (car-safe binding
)))
1698 (if (and (consp binding
) (or (consp spec
) (cl--unused-var-p spec
)))
1700 (expr (car (cdr-safe binding
)))
1701 (temp (last spec
0)))
1702 (if (and (cl--unused-var-p temp
) (null expr
))
1703 nil
;; Don't bother declaring/setting `temp' since it won't
1704 ;; be used when `expr' is nil, anyway.
1705 (when (or (null temp
)
1706 (and (eq body
'setq
) (cl--unused-var-p temp
)))
1707 ;; Prefer a fresh uninterned symbol over "_to", to avoid
1708 ;; warnings that we set an unused variable.
1709 (setq temp
(make-symbol "--cl-var--"))
1710 ;; Make sure this temp variable is locally declared.
1711 (when (eq body
'setq
)
1712 (push (list (list temp
)) cl--loop-bindings
)))
1713 (push (list temp expr
) new
))
1715 (push (list (pop spec
)
1716 (and expr
(list (if spec
'pop
'car
) temp
)))
1718 (setq specs
(nconc (nreverse nspecs
) specs
)))
1719 (push binding new
))))
1721 (let ((set (cons (if par
'cl-psetq
'setq
)
1722 (apply 'nconc
(nreverse new
)))))
1723 (if temps
`(let* ,(nreverse temps
) ,set
) set
))
1724 `(,(if par
'let
'let
*)
1725 ,(nconc (nreverse temps
) (nreverse new
)) ,@body
))))
1727 (defun cl--loop-handle-accum (def &optional func
) ; uses loop-*
1728 (if (eq (car cl--loop-args
) 'into
)
1729 (let ((var (cl--pop2 cl--loop-args
)))
1730 (or (memq var cl--loop-accum-vars
)
1731 (progn (push (list (list var def
)) cl--loop-bindings
)
1732 (push var cl--loop-accum-vars
)))
1734 (or cl--loop-accum-var
1737 (setq cl--loop-accum-var
(make-symbol "--cl-var--"))
1740 (setq cl--loop-result
(if func
(list func cl--loop-accum-var
)
1741 cl--loop-accum-var
))
1742 cl--loop-accum-var
))))
1744 (defun cl--loop-build-ands (clauses)
1745 "Return various representations of (and . CLAUSES).
1746 CLAUSES is a list of Elisp expressions, where clauses of the form
1747 \(progn E1 E2 E3 .. t) are the focus of particular optimizations.
1748 The return value has shape (COND BODY COMBO)
1749 such that COMBO is equivalent to (and . CLAUSES)."
1752 ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
1753 ;; into (progn ,@A ,@B) ,@C.
1755 (if (and (eq (car-safe (car clauses
)) 'progn
)
1756 (eq (car (last (car clauses
))) t
))
1758 (setq clauses
(cons (nconc (butlast (car clauses
))
1759 (if (eq (car-safe (cadr clauses
))
1762 (list (cadr clauses
))))
1764 ;; A final (progn ,@A t) is moved outside of the `and'.
1765 (setq body
(cdr (butlast (pop clauses
)))))
1766 (push (pop clauses
) ands
)))
1767 (setq ands
(or (nreverse ands
) (list t
)))
1768 (list (if (cdr ands
) (cons 'and ands
) (car ands
))
1770 (let ((full (if body
1771 (append ands
(list (cons 'progn
(append body
'(t)))))
1773 (if (cdr full
) (cons 'and full
) (car full
))))))
1776 ;;; Other iteration control structures.
1779 (defmacro cl-do
(steps endtest
&rest body
)
1780 "The Common Lisp `do' loop.
1782 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1785 ((&rest
&or symbolp
(symbolp &optional form form
))
1787 cl-declarations body
)))
1788 (cl--expand-do-loop steps endtest body nil
))
1791 (defmacro cl-do
* (steps endtest
&rest body
)
1792 "The Common Lisp `do*' loop.
1794 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1795 (declare (indent 2) (debug cl-do
))
1796 (cl--expand-do-loop steps endtest body t
))
1798 (defun cl--expand-do-loop (steps endtest body star
)
1800 (,(if star
'let
* 'let
)
1801 ,(mapcar (lambda (c) (if (consp c
) (list (car c
) (nth 1 c
)) c
))
1803 (while (not ,(car endtest
))
1805 ,@(let ((sets (mapcar (lambda (c)
1806 (and (consp c
) (cdr (cdr c
))
1807 (list (car c
) (nth 2 c
))))
1809 (setq sets
(delq nil sets
))
1811 (list (cons (if (or star
(not (cdr sets
)))
1813 (apply 'append sets
))))))
1814 ,@(or (cdr endtest
) '(nil)))))
1817 (defmacro cl-dolist
(spec &rest body
)
1819 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1820 Then evaluate RESULT to get return value, default nil.
1821 An implicit nil block is established around the loop.
1823 \(fn (VAR LIST [RESULT]) BODY...)"
1824 (declare (debug ((symbolp form
&optional form
) cl-declarations body
))
1826 (let ((loop `(dolist ,spec
,@body
)))
1827 (if (advice-member-p 'cl--wrap-in-nil-block
'dolist
)
1828 loop
`(cl-block nil
,loop
))))
1831 (defmacro cl-dotimes
(spec &rest body
)
1832 "Loop a certain number of times.
1833 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1834 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1837 \(fn (VAR COUNT [RESULT]) BODY...)"
1838 (declare (debug cl-dolist
) (indent 1))
1839 (let ((loop `(dotimes ,spec
,@body
)))
1840 (if (advice-member-p 'cl--wrap-in-nil-block
'dotimes
)
1841 loop
`(cl-block nil
,loop
))))
1843 (defvar cl--tagbody-alist nil
)
1846 (defmacro cl-tagbody
(&rest labels-or-stmts
)
1847 "Execute statements while providing for control transfers to labels.
1848 Each element of LABELS-OR-STMTS can be either a label (integer or symbol)
1849 or a `cons' cell, in which case it's taken to be a statement.
1850 This distinction is made before performing macroexpansion.
1851 Statements are executed in sequence left to right, discarding any return value,
1852 stopping only when reaching the end of LABELS-OR-STMTS.
1853 Any statement can transfer control at any time to the statements that follow
1854 one of the labels with the special form (go LABEL).
1855 Labels have lexical scope and dynamic extent."
1857 (first-label (if (consp (car labels-or-stmts
))
1858 'cl--preamble
(pop labels-or-stmts
))))
1859 (let ((block (list first-label
)))
1860 (dolist (label-or-stmt labels-or-stmts
)
1861 (if (consp label-or-stmt
) (push label-or-stmt block
)
1862 ;; Add a "go to next block" to implement the fallthrough.
1863 (unless (eq 'go
(car-safe (car-safe block
)))
1864 (push `(go ,label-or-stmt
) block
))
1865 (push (nreverse block
) blocks
)
1866 (setq block
(list label-or-stmt
))))
1867 (unless (eq 'go
(car-safe (car-safe block
)))
1868 (push `(go cl--exit
) block
))
1869 (push (nreverse block
) blocks
))
1870 (let ((catch-tag (make-symbol "cl--tagbody-tag"))
1871 (cl--tagbody-alist cl--tagbody-alist
))
1872 (push (cons 'cl--exit catch-tag
) cl--tagbody-alist
)
1873 (dolist (block blocks
)
1874 (push (cons (car block
) catch-tag
) cl--tagbody-alist
))
1876 `(let ((next-label ',first-label
))
1878 (not (eq (setq next-label
1883 `((go .
,(lambda (label)
1884 (let ((catch-tag (cdr (assq label cl--tagbody-alist
))))
1886 (error "Unknown cl-tagbody go label `%S'" label
))
1887 `(throw ',catch-tag
',label
))))
1888 ,@macroexpand-all-environment
)))))
1890 (defun cl--prog (binder bindings body
)
1892 (while (eq 'declare
(car-safe (car body
)))
1893 (push (pop body
) decls
))
1897 (cl-tagbody .
,body
)))))
1900 (defmacro cl-prog
(bindings &rest body
)
1901 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1902 Shorthand for (cl-block nil (let BINDINGS (cl-tagbody BODY)))"
1903 (cl--prog 'let bindings body
))
1906 (defmacro cl-prog
* (bindings &rest body
)
1907 "Run BODY like a `cl-tagbody' after setting up the BINDINGS.
1908 Shorthand for (cl-block nil (let* BINDINGS (cl-tagbody BODY)))"
1909 (cl--prog 'let
* bindings body
))
1912 (defmacro cl-do-symbols
(spec &rest body
)
1913 "Loop over all symbols.
1914 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1917 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1919 (debug ((symbolp &optional form form
) cl-declarations body
)))
1920 ;; Apparently this doesn't have an implicit block.
1923 (mapatoms #'(lambda (,(car spec
)) ,@body
)
1924 ,@(and (cadr spec
) (list (cadr spec
))))
1928 (defmacro cl-do-all-symbols
(spec &rest body
)
1929 "Like `cl-do-symbols', but use the default obarray.
1931 \(fn (VAR [RESULT]) BODY...)"
1932 (declare (indent 1) (debug ((symbolp &optional form
) cl-declarations body
)))
1933 `(cl-do-symbols (,(car spec
) nil
,(cadr spec
)) ,@body
))
1939 (defmacro cl-psetq
(&rest args
)
1940 "Set SYMs to the values VALs in parallel.
1941 This is like `setq', except that all VAL forms are evaluated (in order)
1942 before assigning any symbols SYM to the corresponding values.
1944 \(fn SYM VAL SYM VAL ...)"
1945 (declare (debug setq
))
1946 (cons 'cl-psetf args
))
1949 ;;; Binding control structures.
1952 (defmacro cl-progv
(symbols values
&rest body
)
1953 "Bind SYMBOLS to VALUES dynamically in BODY.
1954 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1955 Each symbol in the first list is bound to the corresponding value in the
1956 second list (or to nil if VALUES is shorter than SYMBOLS); then the
1957 BODY forms are executed and their result is returned. This is much like
1958 a `let' form, except that the list of symbols can be computed at run-time."
1959 (declare (indent 2) (debug (form form body
)))
1960 (let ((bodyfun (make-symbol "body"))
1961 (binds (make-symbol "binds"))
1962 (syms (make-symbol "syms"))
1963 (vals (make-symbol "vals")))
1965 (let* ((,syms
,symbols
)
1967 (,bodyfun
(lambda () ,@body
))
1970 (push (list (pop ,syms
) (list 'quote
(pop ,vals
))) ,binds
))
1971 (eval (list 'let
,binds
(list 'funcall
(list 'quote
,bodyfun
))))))))
1973 (defconst cl--labels-magic
(make-symbol "cl--labels-magic"))
1975 (defvar cl--labels-convert-cache nil
)
1977 (defun cl--labels-convert (f)
1978 "Special macro-expander to rename (function F) references in `cl-labels'."
1980 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1981 ;; *after* handling `function', but we want to stop macroexpansion from
1982 ;; being applied infinitely, so we use a cache to return the exact `form'
1983 ;; being expanded even though we don't receive it.
1984 ((eq f
(car cl--labels-convert-cache
)) (cdr cl--labels-convert-cache
))
1986 (let* ((found (assq f macroexpand-all-environment
))
1987 (replacement (and found
1989 (funcall (cdr found
) cl--labels-magic
)))))
1990 (if (and replacement
(eq cl--labels-magic
(car replacement
)))
1992 (let ((res `(function ,f
)))
1993 (setq cl--labels-convert-cache
(cons f res
))
1997 (defmacro cl-flet
(bindings &rest body
)
1998 "Make local function definitions.
1999 Like `cl-labels' but the definitions are not recursive.
2000 Each binding can take the form (FUNC EXP) where
2001 FUNC is the function name, and EXP is an expression that returns the
2002 function value to which it should be bound, or it can take the more common
2003 form \(FUNC ARGLIST BODY...) which is a shorthand
2004 for (FUNC (lambda ARGLIST BODY)).
2006 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
2007 (declare (indent 1) (debug ((&rest
(cl-defun)) cl-declarations body
)))
2008 (let ((binds ()) (newenv macroexpand-all-environment
))
2009 (dolist (binding bindings
)
2010 (let ((var (make-symbol (format "--cl-%s--" (car binding
))))
2011 (args-and-body (cdr binding
)))
2012 (if (and (= (length args-and-body
) 1) (symbolp (car args-and-body
)))
2013 ;; Optimize (cl-flet ((fun var)) body).
2014 (setq var
(car args-and-body
))
2015 (push (list var
(if (= (length args-and-body
) 1)
2017 `(cl-function (lambda .
,args-and-body
))))
2019 (push (cons (car binding
)
2020 (lambda (&rest args
)
2021 (if (eq (car args
) cl--labels-magic
)
2022 (list cl--labels-magic var
)
2023 `(funcall ,var
,@args
))))
2025 ;; FIXME: Eliminate those functions which aren't referenced.
2026 (macroexp-let* (nreverse binds
)
2029 ;; Don't override lexical-let's macro-expander.
2030 (if (assq 'function newenv
) newenv
2031 (cons (cons 'function
#'cl--labels-convert
) newenv
))))))
2034 (defmacro cl-flet
* (bindings &rest body
)
2035 "Make local function definitions.
2036 Like `cl-flet' but the definitions can refer to previous ones.
2038 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
2039 (declare (indent 1) (debug cl-flet
))
2041 ((null bindings
) (macroexp-progn body
))
2042 ((null (cdr bindings
)) `(cl-flet ,bindings
,@body
))
2043 (t `(cl-flet (,(pop bindings
)) (cl-flet* ,bindings
,@body
)))))
2046 (defmacro cl-labels
(bindings &rest body
)
2047 "Make temporary function bindings.
2048 The bindings can be recursive and the scoping is lexical, but capturing them
2049 in closures will only work if `lexical-binding' is in use.
2051 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
2052 (declare (indent 1) (debug cl-flet
))
2053 (let ((binds ()) (newenv macroexpand-all-environment
))
2054 (dolist (binding bindings
)
2055 (let ((var (make-symbol (format "--cl-%s--" (car binding
)))))
2056 (push (list var
`(cl-function (lambda .
,(cdr binding
)))) binds
)
2057 (push (cons (car binding
)
2058 (lambda (&rest args
)
2059 (if (eq (car args
) cl--labels-magic
)
2060 (list cl--labels-magic var
)
2061 (cl-list* 'funcall var args
))))
2063 (macroexpand-all `(letrec ,(nreverse binds
) ,@body
)
2064 ;; Don't override lexical-let's macro-expander.
2065 (if (assq 'function newenv
) newenv
2066 (cons (cons 'function
#'cl--labels-convert
) newenv
)))))
2068 ;; The following ought to have a better definition for use with newer
2071 (defmacro cl-macrolet
(bindings &rest body
)
2072 "Make temporary macro definitions.
2073 This is like `cl-flet', but for macros instead of functions.
2075 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
2078 ((&rest
(&define name
(&rest arg
) cl-declarations-or-string
2080 cl-declarations body
)))
2082 `(cl-macrolet (,(car bindings
)) (cl-macrolet ,(cdr bindings
) ,@body
))
2083 (if (null bindings
) (macroexp-progn body
)
2084 (let* ((name (caar bindings
))
2085 (res (cl--transform-lambda (cdar bindings
) name
)))
2087 (macroexpand-all (macroexp-progn body
)
2089 (eval `(cl-function (lambda ,@(cdr res
))) t
))
2090 macroexpand-all-environment
))))))
2092 (defun cl--sm-macroexpand (orig-fun exp
&optional env
)
2093 "Special macro expander advice used inside `cl-symbol-macrolet'.
2094 This function extends `macroexpand' during macro expansion
2095 of `cl-symbol-macrolet' to additionally expand symbol macros."
2096 (let ((macroexpand-all-environment env
)
2097 (venv (alist-get :cl-symbol-macros env
)))
2100 (setq exp
(funcall orig-fun exp env
))
2103 ;; Perform symbol-macro expansion.
2104 (let ((symval (assq exp venv
)))
2106 (setq exp
(cadr symval
)))))
2108 ;; Convert setq to setf if required by symbol-macro expansion.
2109 (let* ((args (mapcar (lambda (f) (macroexpand f env
))
2112 (while (and p
(symbolp (car p
))) (setq p
(cddr p
)))
2113 (if p
(setq exp
(cons 'setf args
))
2114 (setq exp
(cons 'setq args
))
2115 ;; Don't loop further.
2117 ;; CL's symbol-macrolet used to treat re-bindings as candidates for
2118 ;; expansion (turning the let into a letf if needed), contrary to
2119 ;; Common-Lisp where such re-bindings hide the symbol-macro.
2120 ;; Not sure if there actually is code out there which depends
2121 ;; on this behavior (haven't found any yet).
2122 ;; Such code should explicitly use `cl-letf' instead, I think.
2124 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2125 ;; (let ((letf nil) (found nil) (nbs ()))
2126 ;; (dolist (binding bindings)
2127 ;; (let* ((var (if (symbolp binding) binding (car binding)))
2128 ;; (sm (assq var venv)))
2129 ;; (push (if (not (cdr sm))
2131 ;; (let ((nexp (cadr sm)))
2133 ;; (unless (symbolp nexp) (setq letf t))
2134 ;; (cons nexp (cdr-safe binding))))
2137 ;; (setq exp `(,(if letf
2138 ;; (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
2143 ;; We implement the Common-Lisp behavior, instead (see bug#26073):
2144 ;; The behavior of CL made sense in a dynamically scoped
2145 ;; language, but nowadays, lexical scoping semantics is more often
2147 (`(,(or `let
`let
*) .
,(or `(,bindings .
,body
) dontcare
))
2148 (let ((nbs ()) (found nil
))
2149 (dolist (binding bindings
)
2150 (let* ((var (if (symbolp binding
) binding
(car binding
)))
2151 (val (and found
(consp binding
) (eq 'let
* (car exp
))
2152 (list (macroexpand-all (cadr binding
)
2154 (push (if (assq var venv
)
2155 ;; This binding should hide "its" surrounding
2156 ;; symbol-macro, but given the way macroexpand-all
2157 ;; works (i.e. the `env' we receive as input will
2158 ;; be (re)applied to the code we return), we can't
2159 ;; prevent application of `env' to the
2160 ;; sub-expressions, so we need to α-rename this
2161 ;; variable instead.
2162 (let ((nvar (make-symbol (symbol-name var
))))
2164 (push (list var nvar
) venv
)
2165 (push (cons :cl-symbol-macros venv
) env
)
2166 (cons nvar
(or val
(cdr-safe binding
))))
2167 (if val
(cons var val
) binding
))
2170 (setq exp
`(,(car exp
)
2173 (macroexpand-all (macroexp-progn body
)
2176 ;; Do the same as for `let' but for variables introduced
2177 ;; via other means, such as `lambda' and `condition-case'.
2178 (`(function (lambda ,args .
,body
))
2179 (let ((nargs ()) (found nil
))
2182 ((memq var
'(&optional
&rest
)) var
)
2184 (let ((nvar (make-symbol (symbol-name var
))))
2186 (push (list var nvar
) venv
)
2187 (push (cons :cl-symbol-macros venv
) env
)
2192 (setq exp
`(function
2193 (lambda ,(nreverse nargs
)
2194 .
,(mapcar (lambda (exp)
2195 (macroexpand-all exp env
))
2198 ((and `(condition-case ,var
,exp .
,clauses
)
2199 (guard (assq var venv
)))
2200 (let ((nvar (make-symbol (symbol-name var
))))
2201 (push (list var nvar
) venv
)
2202 (push (cons :cl-symbol-macros venv
) env
)
2204 `(condition-case ,nvar
,(macroexpand-all exp env
)
2208 .
,(mapcar (lambda (exp)
2209 (macroexpand-all exp env
))
2217 (defmacro cl-symbol-macrolet
(bindings &rest body
)
2218 "Make symbol macro definitions.
2219 Within the body FORMs, references to the variable NAME will be replaced
2220 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
2222 \(fn ((NAME EXPANSION) ...) FORM...)"
2223 (declare (indent 1) (debug ((&rest
(symbolp sexp
)) cl-declarations body
)))
2224 (let ((malformed-bindings nil
)
2225 (advised (advice-member-p #'cl--sm-macroexpand
'macroexpand
)))
2226 (dolist (binding bindings
)
2227 (unless (and (consp binding
) (symbolp (car binding
))
2228 (consp (cdr binding
)) (null (cddr binding
)))
2229 (push binding malformed-bindings
)))
2233 (advice-add 'macroexpand
:around
#'cl--sm-macroexpand
))
2234 (let* ((venv (cdr (assq :cl-symbol-macros
2235 macroexpand-all-environment
)))
2237 (macroexpand-all (macroexp-progn body
)
2238 (cons (cons :cl-symbol-macros
2239 (append bindings venv
))
2240 macroexpand-all-environment
))))
2241 (if malformed-bindings
2242 (macroexp--warn-and-return
2243 (format-message "Malformed `cl-symbol-macrolet' binding(s): %S"
2244 (nreverse malformed-bindings
))
2248 (advice-remove 'macroexpand
#'cl--sm-macroexpand
)))))
2250 ;;; Multiple values.
2253 (defmacro cl-multiple-value-bind
(vars form
&rest body
)
2254 "Collect multiple return values.
2255 FORM must return a list; the BODY is then executed with the first N elements
2256 of this list bound (`let'-style) to each of the symbols SYM in turn. This
2257 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
2258 simulate true multiple return values. For compatibility, (cl-values A B C) is
2259 a synonym for (list A B C).
2261 \(fn (SYM...) FORM BODY)"
2262 (declare (indent 2) (debug ((&rest symbolp
) form body
)))
2263 (let ((temp (make-symbol "--cl-var--")) (n -
1))
2264 `(let* ((,temp
,form
)
2265 ,@(mapcar (lambda (v)
2266 (list v
`(nth ,(setq n
(1+ n
)) ,temp
)))
2271 (defmacro cl-multiple-value-setq
(vars form
)
2272 "Collect multiple return values.
2273 FORM must return a list; the first N elements of this list are stored in
2274 each of the symbols SYM in turn. This is analogous to the Common Lisp
2275 `multiple-value-setq' macro, using lists to simulate true multiple return
2276 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
2278 \(fn (SYM...) FORM)"
2279 (declare (indent 1) (debug ((&rest symbolp
) form
)))
2280 (cond ((null vars
) `(progn ,form nil
))
2281 ((null (cdr vars
)) `(setq ,(car vars
) (car ,form
)))
2283 (let* ((temp (make-symbol "--cl-var--")) (n 0))
2284 `(let ((,temp
,form
))
2285 (prog1 (setq ,(pop vars
) (car ,temp
))
2286 (setq ,@(apply #'nconc
2288 (list v
`(nth ,(setq n
(1+ n
))
2296 (defmacro cl-locally
(&rest body
)
2297 "Equivalent to `progn'."
2301 (defmacro cl-the
(type form
)
2302 "Return FORM. If type-checking is enabled, assert that it is of TYPE."
2303 (declare (indent 1) (debug (cl-type-spec form
)))
2304 (if (not (or (not (cl--compiling-file))
2305 (< cl--optimize-speed
3)
2306 (= cl--optimize-safety
3)))
2308 (macroexp-let2 macroexp-copyable-p temp form
2309 `(progn (unless (cl-typep ,temp
',type
)
2310 (signal 'wrong-type-argument
2311 (list ',type
,temp
',form
)))
2314 (defvar cl--proclaim-history t
) ; for future compilers
2315 (defvar cl--declare-stack t
) ; for future compilers
2317 (defun cl--do-proclaim (spec hist
)
2318 (and hist
(listp cl--proclaim-history
) (push spec cl--proclaim-history
))
2319 (cond ((eq (car-safe spec
) 'special
)
2320 (if (boundp 'byte-compile-bound-variables
)
2321 (setq byte-compile-bound-variables
2322 (append (cdr spec
) byte-compile-bound-variables
))))
2324 ((eq (car-safe spec
) 'inline
)
2325 (while (setq spec
(cdr spec
))
2326 (or (memq (get (car spec
) 'byte-optimizer
)
2327 '(nil byte-compile-inline-expand
))
2328 (error "%s already has a byte-optimizer, can't make it inline"
2330 (put (car spec
) 'byte-optimizer
'byte-compile-inline-expand
)))
2332 ((eq (car-safe spec
) 'notinline
)
2333 (while (setq spec
(cdr spec
))
2334 (if (eq (get (car spec
) 'byte-optimizer
)
2335 'byte-compile-inline-expand
)
2336 (put (car spec
) 'byte-optimizer nil
))))
2338 ((eq (car-safe spec
) 'optimize
)
2339 (let ((speed (assq (nth 1 (assq 'speed
(cdr spec
)))
2340 '((0 nil
) (1 t
) (2 t
) (3 t
))))
2341 (safety (assq (nth 1 (assq 'safety
(cdr spec
)))
2342 '((0 t
) (1 t
) (2 t
) (3 nil
)))))
2343 (if speed
(setq cl--optimize-speed
(car speed
)
2344 byte-optimize
(nth 1 speed
)))
2345 (if safety
(setq cl--optimize-safety
(car safety
)
2346 byte-compile-delete-errors
(nth 1 safety
)))))
2348 ((and (eq (car-safe spec
) 'warn
) (boundp 'byte-compile-warnings
))
2349 (while (setq spec
(cdr spec
))
2350 (if (consp (car spec
))
2351 (if (eq (cl-cadar spec
) 0)
2352 (byte-compile-disable-warning (caar spec
))
2353 (byte-compile-enable-warning (caar spec
)))))))
2356 ;;; Process any proclamations made before cl-macs was loaded.
2357 (defvar cl--proclaims-deferred
)
2358 (let ((p (reverse cl--proclaims-deferred
)))
2359 (while p
(cl--do-proclaim (pop p
) t
))
2360 (setq cl--proclaims-deferred nil
))
2363 (defmacro cl-declare
(&rest specs
)
2364 "Declare SPECS about the current function while compiling.
2367 (cl-declare (warn 0))
2369 will turn off byte-compile warnings in the function.
2370 See Info node `(cl)Declarations' for details."
2371 (if (cl--compiling-file)
2373 (if (listp cl--declare-stack
) (push (car specs
) cl--declare-stack
))
2374 (cl--do-proclaim (pop specs
) nil
)))
2377 ;;; The standard modify macros.
2379 ;; `setf' is now part of core Elisp, defined in gv.el.
2382 (defmacro cl-psetf
(&rest args
)
2383 "Set PLACEs to the values VALs in parallel.
2384 This is like `setf', except that all VAL forms are evaluated (in order)
2385 before assigning any PLACEs to the corresponding values.
2387 \(fn PLACE VAL PLACE VAL ...)"
2388 (declare (debug setf
))
2389 (let ((p args
) (simple t
) (vars nil
))
2391 (if (or (not (symbolp (car p
))) (cl--expr-depends-p (nth 1 p
) vars
))
2393 (if (memq (car p
) vars
)
2394 (error "Destination duplicated in psetf: %s" (car p
)))
2396 (or p
(error "Odd number of arguments to cl-psetf"))
2399 `(progn (setq ,@args
) nil
)
2400 (setq args
(reverse args
))
2401 (let ((expr `(setf ,(cadr args
) ,(car args
))))
2402 (while (setq args
(cddr args
))
2403 (setq expr
`(setf ,(cadr args
) (prog1 ,(car args
) ,expr
))))
2404 `(progn ,expr nil
)))))
2407 (defmacro cl-remf
(place tag
)
2408 "Remove TAG from property list PLACE.
2409 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2410 The form returns true if TAG was found and removed, nil otherwise."
2411 (declare (debug (place form
)))
2412 (gv-letplace (tval setter
) place
2413 (macroexp-let2 macroexp-copyable-p ttag tag
2414 `(if (eq ,ttag
(car ,tval
))
2415 (progn ,(funcall setter
`(cddr ,tval
))
2417 (cl--do-remf ,tval
,ttag
)))))
2420 (defmacro cl-shiftf
(place &rest args
)
2421 "Shift left among PLACEs.
2422 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2423 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2426 (declare (debug (&rest place
)))
2429 ((symbolp place
) `(prog1 ,place
(setq ,place
(cl-shiftf ,@args
))))
2431 (gv-letplace (getter setter
) place
2433 ,(funcall setter
`(cl-shiftf ,@args
)))))))
2436 (defmacro cl-rotatef
(&rest args
)
2437 "Rotate left among PLACEs.
2438 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2439 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2442 (declare (debug (&rest place
)))
2443 (if (not (memq nil
(mapcar 'symbolp args
)))
2448 (setq sets
(nconc sets
(list (pop args
) (car args
)))))
2449 `(cl-psetf ,@sets
,(car args
) ,first
)))
2450 (let* ((places (reverse args
))
2451 (temp (make-symbol "--cl-rotatef--"))
2455 (gv-letplace (getter setter
) (pop places
)
2456 `(prog1 ,getter
,(funcall setter form
)))))
2457 (gv-letplace (getter setter
) (car places
)
2458 (macroexp-let* `((,temp
,getter
))
2459 `(progn ,(funcall setter form
) nil
))))))
2461 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2462 ;; previous state. If the getter/setter loses information, that info is
2465 (defun cl--letf (bindings simplebinds binds body
)
2466 ;; It's not quite clear what the semantics of cl-letf should be.
2467 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2468 ;; that the actual assignments ("bindings") should only happen after
2469 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2470 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2471 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2473 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2475 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2476 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2478 (if (and (null binds
) (null simplebinds
)) (macroexp-progn body
)
2479 `(let* (,@(mapcar (lambda (x)
2480 (pcase-let ((`(,vold
,getter
,_setter
,_vnew
) x
))
2481 (list vold getter
)))
2490 ;; If there's no vnew, do nothing.
2491 (`(,_vold
,_getter
,setter
,vnew
)
2492 (funcall setter vnew
))))
2495 ,@(mapcar (lambda (x)
2496 (pcase-let ((`(,vold
,_getter
,setter
,_vnew
) x
))
2497 (funcall setter vold
)))
2499 (let* ((binding (car bindings
))
2500 (place (macroexpand (car binding
) macroexpand-all-environment
)))
2501 (gv-letplace (getter setter
) place
2502 (macroexp-let2 nil vnew
(cadr binding
)
2504 ;; Special-case for simple variables.
2505 (cl--letf (cdr bindings
)
2506 (cons `(,getter
,(if (cdr binding
) vnew getter
))
2509 (cl--letf (cdr bindings
) simplebinds
2510 (cons `(,(make-symbol "old") ,getter
,setter
2511 ,@(if (cdr binding
) (list vnew
)))
2516 (defmacro cl-letf
(bindings &rest body
)
2517 "Temporarily bind to PLACEs.
2518 This is the analogue of `let', but with generalized variables (in the
2519 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2520 VALUE, then the BODY forms are executed. On exit, either normally or
2521 because of a `throw' or error, the PLACEs are set back to their original
2522 values. Note that this macro is *not* available in Common Lisp.
2523 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2524 the PLACE is not modified before executing BODY.
2526 \(fn ((PLACE VALUE) ...) BODY...)"
2527 (declare (indent 1) (debug ((&rest
[&or
(symbolp form
)
2528 (gate gv-place
&optional form
)])
2530 (if (and (not (cdr bindings
)) (cdar bindings
) (symbolp (caar bindings
))
2531 (not (assq (caar bindings
)
2532 (alist-get :cl-symbol-macros macroexpand-all-environment
))))
2533 `(let ,bindings
,@body
)
2534 (cl--letf bindings
() () body
)))
2537 (defmacro cl-letf
* (bindings &rest body
)
2538 "Temporarily bind to PLACEs.
2539 Like `cl-letf' but where the bindings are performed one at a time,
2540 rather than all at the end (i.e. like `let*' rather than like `let')."
2541 (declare (indent 1) (debug cl-letf
))
2542 (dolist (binding (reverse bindings
))
2543 (setq body
(list `(cl-letf (,binding
) ,@body
))))
2544 (macroexp-progn body
))
2547 (defmacro cl-callf
(func place
&rest args
)
2548 "Set PLACE to (FUNC PLACE ARGS...).
2549 FUNC should be an unquoted function name. PLACE may be a symbol,
2550 or any generalized variable allowed by `setf'."
2551 (declare (indent 2) (debug (cl-function place
&rest form
)))
2552 (gv-letplace (getter setter
) place
2553 (let* ((rargs (cons getter args
)))
2555 (if (symbolp func
) (cons func rargs
)
2556 `(funcall #',func
,@rargs
))))))
2559 (defmacro cl-callf2
(func arg1 place
&rest args
)
2560 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2561 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2563 \(fn FUNC ARG1 PLACE ARGS...)"
2564 (declare (indent 3) (debug (cl-function form place
&rest form
)))
2565 (if (and (cl--safe-expr-p arg1
) (cl--simple-expr-p place
) (symbolp func
))
2566 `(setf ,place
(,func
,arg1
,place
,@args
))
2567 (macroexp-let2 nil a1 arg1
2568 (gv-letplace (getter setter
) place
2569 (let* ((rargs (cl-list* a1 getter args
)))
2571 (if (symbolp func
) (cons func rargs
)
2572 `(funcall #',func
,@rargs
))))))))
2575 (defmacro cl-defsubst
(name args
&rest body
)
2576 "Define NAME as a function.
2577 Like `defun', except the function is automatically declared `inline' and
2578 the arguments are immutable.
2579 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2580 surrounded by (cl-block NAME ...).
2581 The function's arguments should be treated as immutable.
2583 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2584 (declare (debug cl-defun
) (indent 2))
2585 (let* ((argns (cl--arglist-args args
))
2586 (real-args (if (eq '&cl-defs
(car args
)) (cddr args
) args
))
2588 ;; (pbody (cons 'progn body))
2590 (while (and p
(eq (cl--expr-contains real-args
(car p
)) 1)) (pop p
))
2592 ,(if p nil
; give up if defaults refer to earlier args
2593 `(cl-define-compiler-macro ,name
2594 ,(if (memq '&key args
)
2595 `(&whole cl-whole
&cl-quote
,@args
)
2596 (cons '&cl-quote args
))
2597 ,(format "compiler-macro for inlining `%s'." name
)
2598 (cl--defsubst-expand
2599 ',argns
'(cl-block ,name
,@(cdr (macroexp-parse-body body
)))
2600 ;; We used to pass `simple' as
2601 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2602 ;; But this is much too simplistic since it
2603 ;; does not pay attention to the argvs (and
2604 ;; cl-expr-access-order itself is also too naive).
2606 ,(and (memq '&key args
) 'cl-whole
) nil
,@argns
)))
2607 (cl-defun ,name
,args
,@body
))))
2609 (defun cl--defsubst-expand (argns body simple whole _unsafe
&rest argvs
)
2610 (if (and whole
(not (cl--safe-expr-p (cons 'progn argvs
)))) whole
2611 (if (cl--simple-exprs-p argvs
) (setq simple t
))
2614 (cl-mapcar (lambda (argn argv
)
2615 (if (or simple
(macroexp-const-p argv
))
2616 (progn (push (cons argn argv
) substs
)
2620 ;; FIXME: `sublis/subst' will happily substitute the symbol
2621 ;; `argn' in places where it's not used as a reference
2623 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2624 ;; scope, leading to name capture.
2625 (setq body
(cond ((null substs
) body
)
2626 ((null (cdr substs
))
2627 (cl-subst (cdar substs
) (caar substs
) body
))
2628 (t (cl--sublis substs body
))))
2629 (if lets
`(let ,lets
,body
) body
))))
2631 (defun cl--sublis (alist tree
)
2632 "Perform substitutions indicated by ALIST in TREE (non-destructively)."
2633 (let ((x (assq tree alist
)))
2637 (cons (cl--sublis alist
(car tree
)) (cl--sublis alist
(cdr tree
))))
2642 (defmacro cl--find-class
(type)
2643 `(get ,type
'cl--class
))
2645 ;; Rather than hard code cl-structure-object, we indirect through this variable
2646 ;; for bootstrapping reasons.
2647 (defvar cl--struct-default-parent nil
)
2650 (defmacro cl-defstruct
(struct &rest descs
)
2651 "Define a struct type.
2652 This macro defines a new data type called NAME that stores data
2653 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2654 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2655 You can use the accessors to set the corresponding slots, via `setf'.
2657 NAME may instead take the form (NAME OPTIONS...), where each
2658 OPTION is either a single keyword or (KEYWORD VALUE) where
2659 KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
2660 :type, :named, :initial-offset, :print-function, or :include.
2662 Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
2663 SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
2664 pairs for that slot.
2665 Currently, only one keyword is supported, `:read-only'. If this has a
2666 non-nil value, that slot cannot be set via `setf'.
2668 \(fn NAME SLOTS...)"
2669 (declare (doc-string 2) (indent 1)
2671 (&define
;Makes top-level form not be wrapped.
2676 (&or
[":conc-name" symbolp
]
2677 [":constructor" symbolp
&optional cl-lambda-list
]
2679 [":predicate" symbolp
]
2680 [":include" symbolp
&rest sexp
] ;; Not finished.
2681 [":print-function" sexp
]
2684 [":initial-offset" natnump
])])]
2686 ;; All the above is for the following def-form.
2687 &rest
&or symbolp
(symbolp &optional def-form
&rest sexp
))))
2688 (let* ((name (if (consp struct
) (car struct
) struct
))
2689 (opts (cdr-safe struct
))
2692 (conc-name (concat (symbol-name name
) "-"))
2693 (constructor (intern (format "make-%s" name
)))
2695 (copier (intern (format "copy-%s" name
)))
2696 (predicate (intern (format "%s-p" name
)))
2697 (print-func nil
) (print-auto nil
)
2698 (safety (if (cl--compiling-file) cl--optimize-safety
3))
2700 ;; There are 4 types of structs:
2701 ;; - `vector' type: means we should use a vector, which can come
2702 ;; with or without a tag `name', which is usually in slot 0
2703 ;; but obeys :initial-offset.
2704 ;; - `list' type: same as `vector' but using lists.
2705 ;; - `record' type: means we should use a record, which necessarily
2706 ;; comes tagged in slot 0. Currently we'll use the `name' as
2707 ;; the tag, but we may want to change it so that the class object
2708 ;; is used as the tag.
2709 ;; - nil type: this is the "pre-record default", which uses a vector
2710 ;; with a tag in slot 0 which is a symbol of the form
2711 ;; `cl-struct-NAME'. We need to still support this for backward
2712 ;; compatibility with old .elc files.
2714 (tag-symbol (intern (format "cl-struct-%s-tags" name
)))
2717 (type nil
) ;nil here means not specified explicitly.
2720 (docstring (if (stringp (car descs
)) (pop descs
)))
2721 pred-form pred-check
)
2722 ;; Can't use `cl-check-type' yet.
2723 (unless (cl--struct-name-p name
)
2724 (signal 'wrong-type-argument
(list 'cl-struct-name-p name
'name
)))
2725 (setq descs
(cons '(cl-tag-slot)
2726 (mapcar (function (lambda (x) (if (consp x
) x
(list x
))))
2729 (let ((opt (if (consp (car opts
)) (caar opts
) (car opts
)))
2730 (args (cdr-safe (pop opts
))))
2731 (cond ((eq opt
:conc-name
)
2733 (setq conc-name
(if (car args
)
2734 (symbol-name (car args
)) ""))))
2735 ((eq opt
:constructor
)
2738 ;; If this defines a constructor of the same name as
2739 ;; the default one, don't define the default.
2740 (if (eq (car args
) constructor
)
2741 (setq constructor nil
))
2742 (push args constrs
))
2743 (if args
(setq constructor
(car args
)))))
2745 (if args
(setq copier
(car args
))))
2746 ((eq opt
:predicate
)
2747 (if args
(setq predicate
(car args
))))
2749 ;; FIXME: Actually, we can include more than once as long as
2750 ;; we include EIEIO classes rather than cl-structs!
2751 (when include-name
(error "Can't :include more than once"))
2752 (setq include-name
(car args
))
2753 (setq include-descs
(mapcar (function
2755 (if (consp x
) x
(list x
))))
2757 ((eq opt
:print-function
)
2758 (setq print-func
(car args
)))
2760 (setq type
(car args
))
2761 (unless (memq type
'(vector list
))
2762 (error "Invalid :type specifier: %s" type
)))
2765 ((eq opt
:initial-offset
)
2766 (setq descs
(nconc (make-list (car args
) '(cl-skip-slot))
2769 (error "Structure option %s unrecognized" opt
)))))
2770 (unless (or include-name type
)
2771 (setq include-name cl--struct-default-parent
))
2772 (when include-name
(setq include
(cl--struct-get-class include-name
)))
2775 `(progn (funcall #',print-func cl-x cl-s cl-n
) t
))
2776 (or type
(and include
(not (cl--struct-class-print include
)))
2778 print-func
(and (or (not (or include type
)) (null print-func
))
2780 (princ ,(format "#S(%s" name
) cl-s
))))))
2782 (let* ((inc-type (cl--struct-class-type include
))
2783 (old-descs (cl-struct-slot-info include
)))
2784 (and type
(not (eq inc-type type
))
2785 (error ":type disagrees with :include for %s" name
))
2786 (while include-descs
2787 (setcar (memq (or (assq (caar include-descs
) old-descs
)
2788 (error "No slot %s in included struct %s"
2789 (caar include-descs
) include
))
2791 (pop include-descs
)))
2792 (setq descs
(append old-descs
(delq (assq 'cl-tag-slot descs
) descs
))
2794 named
(if (memq type
'(vector list
))
2795 (assq 'cl-tag-slot descs
)
2797 (if (cl--struct-class-named include
) (setq named t
)))
2799 (setq named
'true
)))
2800 (or named
(setq descs
(delq (assq 'cl-tag-slot descs
) descs
)))
2801 (when (and (null predicate
) named
)
2802 (setq predicate
(intern (format "cl--struct-%s-p" name
))))
2803 (setq pred-form
(and named
2804 (let ((pos (- (length descs
)
2805 (length (memq (assq 'cl-tag-slot descs
)
2808 ((null type
) ;Record type.
2809 `(memq (type-of cl-x
) ,tag-symbol
))
2811 `(and (vectorp cl-x
)
2812 (>= (length cl-x
) ,(length descs
))
2813 (memq (aref cl-x
,pos
) ,tag-symbol
)))
2814 ((= pos
0) `(memq (car-safe cl-x
) ,tag-symbol
))
2815 (t `(and (consp cl-x
)
2816 (memq (nth ,pos cl-x
) ,tag-symbol
))))))
2817 pred-check
(and pred-form
(> safety
0)
2818 (if (and (eq (cl-caadr pred-form
) 'vectorp
)
2820 (cons 'and
(cl-cdddr pred-form
))
2821 `(,predicate cl-x
))))
2823 (push `(cl-defsubst ,predicate
(cl-x)
2824 (declare (side-effect-free error-free
))
2825 ,(if (eq (car pred-form
) 'and
)
2826 (append pred-form
'(t))
2827 `(and ,pred-form t
)))
2829 (push `(put ',name
'cl-deftype-satisfies
',predicate
) forms
))
2830 (let ((pos 0) (descp descs
))
2832 (let* ((desc (pop descp
))
2834 (if (memq slot
'(cl-tag-slot cl-skip-slot
))
2837 (push (and (eq slot
'cl-tag-slot
) `',tag
)
2839 (if (assq slot descp
)
2840 (error "Duplicate slots named %s in %s" slot name
))
2841 (let ((accessor (intern (format "%s%s" conc-name slot
))))
2843 (push (pop desc
) defaults
)
2844 ;; The arg "cl-x" is referenced by name in eg pred-form
2845 ;; and pred-check, so changing it is not straightforward.
2846 (push `(cl-defsubst ,accessor
(cl-x)
2847 ,(format "Access slot \"%s\" of `%s' struct CL-X."
2849 (declare (side-effect-free t
))
2851 (list `(or ,pred-check
2852 (signal 'wrong-type-argument
2853 (list ',name cl-x
)))))
2854 ,(if (memq type
'(nil vector
)) `(aref cl-x
,pos
)
2855 (if (= pos
0) '(car cl-x
)
2858 (when (cl-oddp (length desc
))
2860 (macroexp--warn-and-return
2861 (format "Missing value for option `%S' of slot `%s' in struct %s!"
2862 (car (last desc
)) slot name
)
2865 (when (and (keywordp (car defaults
))
2866 (not (keywordp (car desc
))))
2867 (let ((kw (car defaults
)))
2869 (macroexp--warn-and-return
2870 (format " I'll take `%s' to be an option rather than a default value."
2875 (setcar defaults nil
))))
2876 (if (plist-get desc
':read-only
)
2877 (push `(gv-define-expander ,accessor
2878 (lambda (_cl-do _cl-x
)
2879 (error "%s is a read-only slot" ',accessor
)))
2881 ;; For normal slots, we don't need to define a setf-expander,
2882 ;; since gv-get can use the compiler macro to get the
2884 ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
2885 ;; ;; If cl is loaded only for compilation,
2886 ;; ;; the call to cl--struct-setf-expander would
2887 ;; ;; cause a warning because it may not be
2888 ;; ;; defined at run time. Suppress that warning.
2890 ;; (declare-function
2891 ;; cl--struct-setf-expander "cl-macs"
2892 ;; (x name accessor pred-form pos))
2893 ;; (cl--struct-setf-expander
2894 ;; cl-val cl-x ',name ',accessor
2895 ;; ,(and pred-check `',pred-check)
2901 (list `(princ ,(format " %s" slot
) cl-s
)
2902 `(prin1 (,accessor cl-x
) cl-s
)))))))
2903 (setq pos
(1+ pos
))))
2904 (setq slots
(nreverse slots
)
2905 defaults
(nreverse defaults
))
2907 (push `(defalias ',copier
#'copy-sequence
)
2910 (push (list constructor
2911 (cons '&key
(delq nil
(copy-sequence slots
))))
2913 (pcase-dolist (`(,cname
,args
,doc
) constrs
)
2914 (let* ((anames (cl--arglist-args args
))
2915 (make (cl-mapcar (function (lambda (s d
) (if (memq s anames
) s d
)))
2917 (push `(cl-defsubst ,cname
2918 (&cl-defs
(nil ,@descs
) ,@args
)
2919 ,(if (stringp doc
) doc
2920 (format "Constructor for objects of type `%s'." name
))
2921 ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs
)))
2922 '((declare (side-effect-free t
))))
2923 (,(or type
#'record
) ,@make
))
2925 (if print-auto
(nconc print-func
(list '(princ ")" cl-s
) t
)))
2926 ;; Don't bother adding to cl-custom-print-functions since it's not used
2927 ;; by anything anyway!
2929 ;; (push `(if (boundp 'cl-custom-print-functions)
2931 ;; ;; The auto-generated function does not pay attention to
2932 ;; ;; the depth argument cl-n.
2933 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2934 ;; (and ,pred-form ,print-func))
2935 ;; cl-custom-print-functions))
2938 (defvar ,tag-symbol
)
2940 ;; Call cl-struct-define during compilation as well, so that
2941 ;; a subsequent cl-defstruct in the same file can correctly include this
2942 ;; struct as a parent.
2944 (cl-struct-define ',name
,docstring
',include-name
2945 ',(or type
'record
) ,(eq named t
) ',descs
2946 ',tag-symbol
',tag
',print-auto
))
2949 ;;; Add cl-struct support to pcase
2951 (defun cl--struct-all-parents (class)
2952 (when (cl--struct-class-p class
)
2954 (classes (list class
)))
2956 (while (let ((class (pop classes
)))
2960 (cl--class-parents class
)))))
2964 (pcase-defmacro cl-struct
(type &rest fields
)
2965 "Pcase patterns to match cl-structs.
2966 Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
2967 field NAME is matched against PAT, or they can be of the form NAME which
2968 is a shorthand for (NAME NAME)."
2969 (declare (debug (sexp &rest
[&or
(sexp pcase-PAT
) sexp
])))
2970 `(and (pred (pcase--flip cl-typep
',type
))
2973 (let* ((name (if (consp field
) (car field
) field
))
2974 (pat (if (consp field
) (cadr field
) field
)))
2975 `(app ,(if (eq (cl-struct-sequence-type type
) 'list
)
2976 `(nth ,(cl-struct-slot-offset type name
))
2977 `(pcase--flip aref
,(cl-struct-slot-offset type name
)))
2981 (defun cl--defstruct-predicate (type)
2982 (let ((cons (assq (cl-struct-sequence-type type
)
2990 (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2
)
2991 "Extra special cases for `cl-typep' predicates."
2992 (let* ((x1 pred1
) (x2 pred2
)
2994 (and (eq 'pcase--flip
(car-safe x1
)) (setq x1
(cdr x1
))
2995 (eq 'cl-typep
(car-safe x1
)) (setq x1
(cdr x1
))
2996 (null (cdr-safe x1
)) (setq x1
(car x1
))
2997 (eq 'quote
(car-safe x1
)) (cadr x1
)))
2999 (and (eq 'pcase--flip
(car-safe x2
)) (setq x2
(cdr x2
))
3000 (eq 'cl-typep
(car-safe x2
)) (setq x2
(cdr x2
))
3001 (null (cdr-safe x2
)) (setq x2
(car x2
))
3002 (eq 'quote
(car-safe x2
)) (cadr x2
))))
3004 (and (symbolp t1
) (symbolp t2
)
3005 (let ((c1 (cl--find-class t1
))
3006 (c2 (cl--find-class t2
)))
3008 (not (or (memq c1
(cl--struct-all-parents c2
))
3009 (memq c2
(cl--struct-all-parents c1
)))))))
3010 (let ((c1 (and (symbolp t1
) (cl--find-class t1
))))
3011 (and c1
(cl--struct-class-p c1
)
3012 (funcall orig
(cl--defstruct-predicate t1
)
3014 (let ((c2 (and (symbolp t2
) (cl--find-class t2
))))
3015 (and c2
(cl--struct-class-p c2
)
3017 (cl--defstruct-predicate t2
))))
3018 (funcall orig pred1 pred2
))))
3019 (advice-add 'pcase--mutually-exclusive-p
3020 :around
#'cl--pcase-mutually-exclusive-p
)
3023 (defun cl-struct-sequence-type (struct-type)
3024 "Return the sequence used to build STRUCT-TYPE.
3025 STRUCT-TYPE is a symbol naming a struct type. Return `record',
3026 `vector`, or `list' if STRUCT-TYPE is a struct type, nil otherwise."
3027 (declare (side-effect-free t
) (pure t
))
3028 (cl--struct-class-type (cl--struct-get-class struct-type
)))
3030 (defun cl-struct-slot-info (struct-type)
3031 "Return a list of slot names of struct STRUCT-TYPE.
3032 Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
3033 slot name symbol and OPTS is a list of slot options given to
3034 `cl-defstruct'. Dummy slots that represent the struct name and
3035 slots skipped by :initial-offset may appear in the list."
3036 (declare (side-effect-free t
) (pure t
))
3037 (let* ((class (cl--struct-get-class struct-type
))
3038 (slots (cl--struct-class-slots class
))
3039 (type (cl--struct-class-type class
))
3040 (descs (if type
() (list '(cl-tag-slot)))))
3041 (dotimes (i (length slots
))
3042 (let ((slot (aref slots i
)))
3043 (push `(,(cl--slot-descriptor-name slot
)
3044 ,(cl--slot-descriptor-initform slot
)
3045 ,@(if (not (eq (cl--slot-descriptor-type slot
) t
))
3046 `(:type
,(cl--slot-descriptor-type slot
)))
3047 ,@(cl--slot-descriptor-props slot
))
3051 (define-error 'cl-struct-unknown-slot
"struct %S has no slot %S")
3053 (defun cl-struct-slot-offset (struct-type slot-name
)
3054 "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
3055 The returned zero-based slot index is relative to the start of
3056 the structure data type and is adjusted for any structure name
3057 and :initial-offset slots. Signal error if struct STRUCT-TYPE
3058 does not contain SLOT-NAME."
3059 (declare (side-effect-free t
) (pure t
))
3060 (or (gethash slot-name
3061 (cl--class-index-table (cl--struct-get-class struct-type
)))
3062 (signal 'cl-struct-unknown-slot
(list struct-type slot-name
))))
3064 (defvar byte-compile-function-environment
)
3065 (defvar byte-compile-macro-environment
)
3067 (defun cl--macroexp-fboundp (sym)
3068 "Return non-nil if SYM will be bound when we run the code.
3069 Of course, we really can't know that for sure, so it's just a heuristic."
3071 (and (cl--compiling-file)
3072 (or (cdr (assq sym byte-compile-function-environment
))
3073 (cdr (assq sym byte-compile-macro-environment
))))))
3075 (put 'null
'cl-deftype-satisfies
#'null
)
3076 (put 'atom
'cl-deftype-satisfies
#'atom
)
3077 (put 'real
'cl-deftype-satisfies
#'numberp
)
3078 (put 'fixnum
'cl-deftype-satisfies
#'integerp
)
3079 (put 'base-char
'cl-deftype-satisfies
#'characterp
)
3080 (put 'character
'cl-deftype-satisfies
#'natnump
)
3084 (define-inline cl-typep
(val type
)
3085 (inline-letevals (val)
3086 (pcase (inline-const-val type
)
3087 ((and `(,name .
,args
) (guard (get name
'cl-deftype-handler
)))
3089 (cl-typep ,val
',(apply (get name
'cl-deftype-handler
) args
))))
3090 (`(,(and name
(or 'integer
'float
'real
'number
))
3091 .
,(or `(,min
,max
) pcase--dontcare
))
3093 (and (cl-typep ,val
',name
)
3094 ,(if (memq min
'(* nil
)) t
3096 (inline-quote (> ,val
',(car min
)))
3097 (inline-quote (>= ,val
',min
))))
3098 ,(if (memq max
'(* nil
)) t
3100 (inline-quote (< ,val
',(car max
)))
3101 (inline-quote (<= ,val
',max
)))))))
3102 (`(not ,type
) (inline-quote (not (cl-typep ,val
',type
))))
3103 (`(,(and name
(or 'and
'or
)) .
,types
)
3105 ((null types
) (inline-quote ',(eq name
'and
)))
3107 (inline-quote (cl-typep ,val
',(car types
))))
3109 (let ((head (car types
))
3110 (rest `(,name .
,(cdr types
))))
3113 (inline-quote (and (cl-typep ,val
',head
)
3114 (cl-typep ,val
',rest
))))
3116 (inline-quote (or (cl-typep ,val
',head
)
3117 (cl-typep ,val
',rest
)))))))))
3118 (`(eql ,v
) (inline-quote (and (eql ,val
',v
) t
)))
3119 (`(member .
,args
) (inline-quote (and (memql ,val
',args
) t
)))
3120 (`(satisfies ,pred
) (inline-quote (funcall #',pred
,val
)))
3121 ((and (pred symbolp
) type
(guard (get type
'cl-deftype-handler
)))
3123 (cl-typep ,val
',(funcall (get type
'cl-deftype-handler
)))))
3124 ((and (pred symbolp
) type
(guard (get type
'cl-deftype-satisfies
)))
3125 (inline-quote (funcall #',(get type
'cl-deftype-satisfies
) ,val
)))
3126 ((and (or 'nil
't
) type
) (inline-quote ',type
))
3127 ((and (pred symbolp
) type
)
3128 (let* ((name (symbol-name type
))
3129 (namep (intern (concat name
"p"))))
3131 ((cl--macroexp-fboundp namep
) (inline-quote (funcall #',namep
,val
)))
3132 ((cl--macroexp-fboundp
3133 (setq namep
(intern (concat name
"-p"))))
3134 (inline-quote (funcall #',namep
,val
)))
3135 ((cl--macroexp-fboundp type
) (inline-quote (funcall #',type
,val
)))
3136 (t (error "Unknown type %S" type
)))))
3137 (type (error "Bad type spec: %s" type
)))))
3141 (defmacro cl-check-type
(form type
&optional string
)
3142 "Verify that FORM is of type TYPE; signal an error if not.
3143 STRING is an optional description of the desired type."
3144 (declare (debug (place cl-type-spec
&optional stringp
)))
3145 (and (or (not (cl--compiling-file))
3146 (< cl--optimize-speed
3) (= cl--optimize-safety
3))
3147 (macroexp-let2 macroexp-copyable-p temp form
3148 `(progn (or (cl-typep ,temp
',type
)
3149 (signal 'wrong-type-argument
3150 (list ,(or string
`',type
) ,temp
',form
)))
3154 (defmacro cl-assert
(form &optional show-args string
&rest args
)
3155 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
3156 "Verify that FORM returns non-nil; signal an error if not.
3157 Second arg SHOW-ARGS means to include arguments of FORM in message.
3158 Other args STRING and ARGS... are arguments to be passed to `error'.
3159 They are not evaluated unless the assertion fails. If STRING is
3160 omitted, a default message listing FORM itself is used."
3161 (declare (debug (form &rest form
)))
3162 (and (or (not (cl--compiling-file))
3163 (< cl--optimize-speed
3) (= cl--optimize-safety
3))
3164 (let ((sargs (and show-args
3165 (delq nil
(mapcar (lambda (x)
3166 (unless (macroexp-const-p x
)
3168 (cdr-safe form
))))))
3171 (cl--assertion-failed
3172 ',form
,@(if (or string sargs args
)
3173 `(,string
(list ,@sargs
) (list ,@args
)))))
3176 ;;; Compiler macros.
3179 (defmacro cl-define-compiler-macro
(func args
&rest body
)
3180 "Define a compiler-only macro.
3181 This is like `defmacro', but macro expansion occurs only if the call to
3182 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
3183 for optimizing the way calls to FUNC are compiled; the form returned by
3184 BODY should do the same thing as a call to the normal function called
3185 FUNC, though possibly more efficiently. Note that, like regular macros,
3186 compiler macros are expanded repeatedly until no further expansions are
3187 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
3188 original function call alone by declaring an initial `&whole foo' parameter
3189 and then returning foo."
3190 (declare (debug cl-defmacro
) (indent 2))
3191 (let ((p args
) (res nil
))
3192 (while (consp p
) (push (pop p
) res
))
3193 (setq args
(nconc (nreverse res
) (and p
(list '&rest p
)))))
3194 ;; FIXME: The code in bytecomp mishandles top-level expressions that define
3195 ;; uninterned functions. E.g. it would generate code like:
3196 ;; (defalias '#1=#:foo--cmacro #[514 ...])
3197 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
3198 ;; So we circumvent this by using an interned name.
3199 (let ((fname (intern (concat (symbol-name func
) "--cmacro"))))
3201 ;; Name the compiler-macro function, so that `symbol-file' can find it.
3202 (cl-defun ,fname
,(if (memq '&whole args
) (delq '&whole args
)
3203 (cons '_cl-whole-arg args
))
3205 (put ',func
'compiler-macro
#',fname
))))
3208 (defun cl-compiler-macroexpand (form)
3209 "Like `macroexpand', but for compiler macros.
3210 Expands FORM repeatedly until no further expansion is possible.
3211 Returns FORM unchanged if it has no compiler macro, or if it has a
3212 macro that returns its `&whole' argument."
3214 (let ((func (car-safe form
)) (handler nil
))
3215 (while (and (symbolp func
)
3216 (not (setq handler
(get func
'compiler-macro
)))
3218 (or (not (autoloadp (symbol-function func
)))
3219 (autoload-do-load (symbol-function func
) func
)))
3220 (setq func
(symbol-function func
)))
3222 (not (eq form
(setq form
(apply handler form
(cdr form
))))))))
3225 ;; Optimize away unused block-wrappers.
3227 (defvar cl--active-block-names nil
)
3229 (cl-define-compiler-macro cl--block-wrapper
(cl-form)
3230 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form
)) nil
))
3231 (cl--active-block-names (cons cl-entry cl--active-block-names
))
3232 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
3233 (macroexp-progn (cddr cl-form
))
3234 macroexpand-all-environment
)))
3235 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
3236 ;; to indicate that this return value is already fully expanded.
3238 `(catch ,(nth 1 cl-form
) ,@(macroexp-unprogn cl-body
))
3241 (cl-define-compiler-macro cl--block-throw
(cl-tag cl-value
)
3242 (let ((cl-found (assq (nth 1 cl-tag
) cl--active-block-names
)))
3243 (if cl-found
(setcdr cl-found t
)))
3244 `(throw ,cl-tag
,cl-value
))
3246 ;; Compile-time optimizations for some functions defined in this package.
3248 (defun cl--compiler-macro-member (form a list
&rest keys
)
3249 (let ((test (and (= (length keys
) 2) (eq (car keys
) :test
)
3250 (cl--const-expr-val (nth 1 keys
)))))
3251 (cond ((eq test
'eq
) `(memq ,a
,list
))
3252 ((eq test
'equal
) `(member ,a
,list
))
3253 ((or (null keys
) (eq test
'eql
)) `(memql ,a
,list
))
3256 (defun cl--compiler-macro-assoc (form a list
&rest keys
)
3257 (let ((test (and (= (length keys
) 2) (eq (car keys
) :test
)
3258 (cl--const-expr-val (nth 1 keys
)))))
3259 (cond ((eq test
'eq
) `(assq ,a
,list
))
3260 ((eq test
'equal
) `(assoc ,a
,list
))
3261 ((and (macroexp-const-p a
) (or (null keys
) (eq test
'eql
)))
3262 (if (floatp (cl--const-expr-val a
))
3263 `(assoc ,a
,list
) `(assq ,a
,list
)))
3267 (defun cl--compiler-macro-adjoin (form a list
&rest keys
)
3268 (if (memq :key keys
) form
3269 (macroexp-let2* macroexp-copyable-p
((va a
) (vlist list
))
3270 `(if (cl-member ,va
,vlist
,@keys
) ,vlist
(cons ,va
,vlist
)))))
3272 (defun cl--compiler-macro-get (_form sym prop
&optional def
)
3274 `(cl-getf (symbol-plist ,sym
) ,prop
,def
)
3277 (dolist (y '(cl-first cl-second cl-third cl-fourth
3278 cl-fifth cl-sixth cl-seventh
3279 cl-eighth cl-ninth cl-tenth
3280 cl-rest cl-endp cl-plusp cl-minusp
3281 cl-caaar cl-caadr cl-cadar
3282 cl-caddr cl-cdaar cl-cdadr
3283 cl-cddar cl-cdddr cl-caaaar
3284 cl-caaadr cl-caadar cl-caaddr
3285 cl-cadaar cl-cadadr cl-caddar
3286 cl-cadddr cl-cdaaar cl-cdaadr
3287 cl-cdadar cl-cdaddr cl-cddaar
3288 cl-cddadr cl-cdddar cl-cddddr
))
3289 (put y
'side-effect-free t
))
3291 ;;; Things that are inline.
3292 (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
3293 cl-notevery cl-revappend cl-nreconc gethash
))
3295 ;;; Things that are side-effect-free.
3296 (mapc (lambda (x) (function-put x
'side-effect-free t
))
3297 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
3298 cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
3299 cl-subseq cl-list-length cl-get cl-getf
))
3301 ;;; Things that are side-effect-and-error-free.
3302 (mapc (lambda (x) (function-put x
'side-effect-free
'error-free
))
3303 '(eql cl-list
* cl-subst cl-acons cl-equalp
3304 cl-random-state-p copy-tree cl-sublis
))
3306 ;;; Types and assertions.
3309 (defmacro cl-deftype
(name arglist
&rest body
)
3310 "Define NAME as a new data type.
3311 The type name can then be used in `cl-typecase', `cl-check-type', etc."
3312 (declare (debug cl-defmacro
) (doc-string 3) (indent 2))
3313 `(cl-eval-when (compile load eval
)
3314 (put ',name
'cl-deftype-handler
3315 (cl-function (lambda (&cl-defs
('*) ,@arglist
) ,@body
)))))
3317 (cl-deftype extended-char
() `(and character
(not base-char
)))
3319 ;;; Additional functions that we can now define because we've defined
3320 ;;; `cl-defsubst' and `cl-typep'.
3322 (define-inline cl-struct-slot-value
(struct-type slot-name inst
)
3323 "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
3324 STRUCT and SLOT-NAME are symbols. INST is a structure instance."
3325 (declare (side-effect-free t
))
3326 (inline-letevals (struct-type slot-name inst
)
3329 (unless (cl-typep ,inst
,struct-type
)
3330 (signal 'wrong-type-argument
(list ,struct-type
,inst
)))
3331 ;; We could use `elt', but since the byte compiler will resolve the
3332 ;; branch below at compile time, it's more efficient to use the
3333 ;; type-specific accessor.
3334 (if (eq (cl-struct-sequence-type ,struct-type
) 'list
)
3335 (nth (cl-struct-slot-offset ,struct-type
,slot-name
) ,inst
)
3336 (aref ,inst
(cl-struct-slot-offset ,struct-type
,slot-name
)))))))
3338 (run-hooks 'cl-macs-load-hook
)
3341 ;; byte-compile-dynamic: t
3342 ;; generated-autoload-file: "cl-loaddefs.el"
3347 ;;; cl-macs.el ends here