1 ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 1993, 2001-2015 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 <http://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
)
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
))))
176 (defun cl-gentemp (&optional prefix
)
177 "Generate a new interned symbol with a unique name.
178 The name is made by appending a number to PREFIX, default \"G\"."
179 (let ((pfix (if (stringp prefix
) prefix
"G"))
181 (while (intern-soft (setq name
(format "%s%d" pfix cl--gensym-counter
)))
182 (setq cl--gensym-counter
(1+ cl--gensym-counter
)))
186 ;;; Program structure.
188 (def-edebug-spec cl-declarations
189 (&rest
("cl-declare" &rest sexp
)))
191 (def-edebug-spec cl-declarations-or-string
192 (&or stringp cl-declarations
))
194 (def-edebug-spec cl-lambda-list
196 [&optional
["&optional" cl-
&optional-arg
&rest cl-
&optional-arg
]]
197 [&optional
["&rest" arg
]]
198 [&optional
["&key" [cl-
&key-arg
&rest cl-
&key-arg
]
199 &optional
"&allow-other-keys"]]
200 [&optional
["&aux" &rest
201 &or
(symbolp &optional def-form
) symbolp
]]
204 (def-edebug-spec cl-
&optional-arg
205 (&or
(arg &optional def-form arg
) arg
))
207 (def-edebug-spec cl-
&key-arg
208 (&or
([&or
(symbolp arg
) arg
] &optional def-form arg
) arg
))
210 (def-edebug-spec cl-type-spec sexp
)
212 (defconst cl--lambda-list-keywords
213 '(&optional
&rest
&key
&allow-other-keys
&aux
&whole
&body
&environment
))
215 ;; Internal hacks used in formal arg lists:
216 ;; - &cl-quote: Added to formal-arglists to mean that any default value
217 ;; mentioned in the formal arglist should be considered as implicitly
218 ;; quoted rather than evaluated. This is used in `cl-defsubst' when
219 ;; performing compiler-macro-expansion, since at that time the
220 ;; arguments hold expressions rather than values.
221 ;; - &cl-defs (DEF . DEFS): Gives the default value to use for missing
222 ;; optional arguments which don't have an explicit default value.
223 ;; DEFS is an alist mapping vars to their default default value.
224 ;; and DEF is the default default to use for all other vars.
226 (defvar cl--bind-block
) ;Name of surrounding block, only use for `signal' data.
227 (defvar cl--bind-defs
) ;(DEF . DEFS) giving the "default default" for optargs.
228 (defvar cl--bind-enquote
) ;Non-nil if &cl-quote was in the formal arglist!
229 (defvar cl--bind-lets
) (defvar cl--bind-forms
)
231 (defun cl--transform-lambda (form bind-block
)
232 "Transform a function form FORM of name BIND-BLOCK.
233 BIND-BLOCK is the name of the symbol to which the function will be bound,
234 and which will be used for the name of the `cl-block' surrounding the
236 FORM is of the form (ARGS . BODY)."
237 (let* ((args (car form
)) (body (cdr form
)) (orig-args args
)
238 (cl--bind-block bind-block
) (cl--bind-defs nil
) (cl--bind-enquote nil
)
239 (parsed-body (macroexp-parse-body body
))
240 (header (car parsed-body
)) (simple-args nil
))
241 (setq body
(cdr parsed-body
))
242 ;; "(. X) to (&rest X)" conversion already done in cl--do-arglist, but we
243 ;; do it here as well, so as to be able to see if we can avoid
245 (setq args
(if (listp args
) (cl-copy-list args
) (list '&rest args
)))
246 (let ((p (last args
))) (if (cdr p
) (setcdr p
(list '&rest
(cdr p
)))))
247 (let ((cl-defs (memq '&cl-defs args
)))
249 (setq cl--bind-defs
(cadr cl-defs
))
250 ;; Remove "&cl-defs DEFS" from args.
251 (setcdr cl-defs
(cddr cl-defs
))
252 (setq args
(delq '&cl-defs args
))))
253 (if (setq cl--bind-enquote
(memq '&cl-quote args
))
254 (setq args
(delq '&cl-quote args
)))
255 (if (memq '&whole args
) (error "&whole not currently implemented"))
256 (let* ((p (memq '&environment args
))
258 (if p
(setq args
(nconc (delq (car p
) (delq v args
))
259 `(&aux
(,v macroexpand-all-environment
))))))
260 ;; Take away all the simple args whose parsing can be handled more
261 ;; efficiently by a plain old `lambda' than the manual parsing generated
262 ;; by `cl--do-arglist'.
263 (let ((optional nil
))
264 (while (and args
(symbolp (car args
))
265 (not (memq (car args
) '(nil &rest
&body
&key
&aux
)))
267 ;; Optional args whose default is nil are simple.
268 (null (nth 1 (assq (car args
) (cdr cl--bind-defs
)))))
269 (not (and (eq (car args
) '&optional
) (setq optional t
)
270 (car cl--bind-defs
))))
271 (push (pop args
) simple-args
))
273 (if args
(push '&optional args
))
274 ;; Don't keep a dummy trailing &optional without actual optional args.
275 (if (eq '&optional
(car simple-args
)) (pop simple-args
))))
276 (or (eq cl--bind-block
'cl-none
)
277 (setq body
(list `(cl-block ,cl--bind-block
,@body
))))
278 (let* ((cl--bind-lets nil
) (cl--bind-forms nil
)
282 ((eq (car args
) '&aux
)
284 (setq cl--bind-lets
(nreverse cl--bind-lets
))
286 (t ;; `simple-args' doesn't handle all the parsing that we need,
287 ;; so we pass the rest to cl--do-arglist which will do
289 (let ((slen (length simple-args
)))
290 (when (memq '&optional simple-args
)
293 ;; Macro expansion can take place in the middle of
294 ;; apparently harmless computation, so it should not
295 ;; touch the match-data.
298 (cons (help-add-fundoc-usage
299 (if (stringp (car header
)) (pop header
))
300 ;; Be careful with make-symbol and (back)quote,
302 (let ((print-gensym nil
) (print-quoted t
))
303 (format "%S" (cons 'fn
(cl--make-usage-args
306 ;; FIXME: we'd want to choose an arg name for the &rest param
307 ;; and pass that as `expr' to cl--do-arglist, but that ends up
308 ;; generating code with a redundant let-binding, so we instead
309 ;; pass a dummy and then look in cl--bind-lets to find what var
310 ;; this was bound to.
311 (cl--do-arglist args
:dummy slen
)
312 (setq cl--bind-lets
(nreverse cl--bind-lets
))
313 ;; (cl-assert (eq :dummy (nth 1 (car cl--bind-lets))))
314 (list '&rest
(car (pop cl--bind-lets
))))))))
316 (,@(nreverse simple-args
) ,@rest-args
)
318 ,(macroexp-let* cl--bind-lets
320 `(,@(nreverse cl--bind-forms
)
324 (defmacro cl-defun
(name args
&rest body
)
325 "Define NAME as a function.
326 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
327 and BODY is implicitly surrounded by (cl-block NAME ...).
329 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
331 ;; Same as defun but use cl-lambda-list.
332 (&define
[&or name
("setf" :name setf name
)]
334 cl-declarations-or-string
335 [&optional
("interactive" interactive
)]
339 (let* ((res (cl--transform-lambda (cons args body
) name
))
340 (form `(defun ,name
,@(cdr res
))))
341 (if (car res
) `(progn ,(car res
) ,form
) form
)))
344 (defmacro cl-iter-defun
(name args
&rest body
)
345 "Define NAME as a generator function.
346 Like normal `iter-defun', except ARGLIST allows full Common Lisp conventions,
347 and BODY is implicitly surrounded by (cl-block NAME ...).
349 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
351 ;; Same as iter-defun but use cl-lambda-list.
352 (&define
[&or name
("setf" :name setf name
)]
354 cl-declarations-or-string
355 [&optional
("interactive" interactive
)]
360 (let* ((res (cl--transform-lambda (cons args body
) name
))
361 (form `(iter-defun ,name
,@(cdr res
))))
362 (if (car res
) `(progn ,(car res
) ,form
) form
)))
364 ;; The lambda list for macros is different from that of normal lambdas.
365 ;; Note that &environment is only allowed as first or last items in the
368 (def-edebug-spec cl-macro-list
369 (([&optional
"&environment" arg
]
371 [&optional
["&optional" &rest
372 &or
(cl-macro-arg &optional def-form cl-macro-arg
) arg
]]
373 [&optional
[[&or
"&rest" "&body"] cl-macro-arg
]]
374 [&optional
["&key" [&rest
375 [&or
([&or
(symbolp cl-macro-arg
) arg
]
376 &optional def-form cl-macro-arg
)
378 &optional
"&allow-other-keys"]]
379 [&optional
["&aux" &rest
380 &or
(symbolp &optional def-form
) symbolp
]]
381 [&optional
"&environment" arg
]
384 (def-edebug-spec cl-macro-arg
385 (&or arg cl-macro-list1
))
387 (def-edebug-spec cl-macro-list1
388 (([&optional
"&whole" arg
] ;; only allowed at lower levels
390 [&optional
["&optional" &rest
391 &or
(cl-macro-arg &optional def-form cl-macro-arg
) arg
]]
392 [&optional
[[&or
"&rest" "&body"] cl-macro-arg
]]
393 [&optional
["&key" [&rest
394 [&or
([&or
(symbolp cl-macro-arg
) arg
]
395 &optional def-form cl-macro-arg
)
397 &optional
"&allow-other-keys"]]
398 [&optional
["&aux" &rest
399 &or
(symbolp &optional def-form
) symbolp
]]
403 (defmacro cl-defmacro
(name args
&rest body
)
404 "Define NAME as a macro.
405 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
406 and BODY is implicitly surrounded by (cl-block NAME ...).
408 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
410 (&define name cl-macro-list cl-declarations-or-string def-body
))
413 (let* ((res (cl--transform-lambda (cons args body
) name
))
414 (form `(defmacro ,name
,@(cdr res
))))
415 (if (car res
) `(progn ,(car res
) ,form
) form
)))
417 (def-edebug-spec cl-lambda-expr
418 (&define
("lambda" cl-lambda-list
419 ;;cl-declarations-or-string
420 ;;[&optional ("interactive" interactive)]
423 ;; Redefine function-form to also match cl-function
424 (def-edebug-spec function-form
425 ;; form at the end could also handle "function",
426 ;; but recognize it specially to avoid wrapping function forms.
427 (&or
([&or
"quote" "function"] &or symbolp lambda-expr
)
428 ("cl-function" cl-function
)
432 (defmacro cl-function
(func)
433 "Introduce a function.
434 Like normal `function', except that if argument is a lambda form,
435 its argument list allows full Common Lisp conventions."
436 (declare (debug (&or symbolp cl-lambda-expr
)))
437 (if (eq (car-safe func
) 'lambda
)
438 (let* ((res (cl--transform-lambda (cdr func
) 'cl-none
))
439 (form `(function (lambda .
,(cdr res
)))))
440 (if (car res
) `(progn ,(car res
) ,form
) form
))
443 (defun cl--make-usage-var (x)
444 "X can be a var or a (destructuring) lambda-list."
446 ((symbolp x
) (make-symbol (upcase (symbol-name x
))))
447 ((consp x
) (cl--make-usage-args x
))
450 (defun cl--make-usage-args (arglist)
451 (let ((aux (ignore-errors (cl-position '&aux arglist
))))
453 ;; `&aux' args aren't arguments, so let's just drop them from the
455 (setq arglist
(cl-subseq arglist
0 aux
))))
456 (if (cdr-safe (last arglist
)) ;Not a proper list.
457 (let* ((last (last arglist
))
462 (nconc (cl--make-usage-args arglist
) (cl--make-usage-var tail
)))
464 ;; `orig-args' can contain &cl-defs.
465 (let ((x (memq '&cl-defs arglist
)))
466 (when x
(setq arglist
(delq (car x
) (remq (cadr x
) arglist
)))))
471 (let ((first (aref (symbol-name x
) 0)))
474 ;; Strip a leading underscore, since it only
475 ;; means that this argument is unused.
476 (make-symbol (upcase (if (eq ?_ first
)
477 (substring (symbol-name x
) 1)
478 (symbol-name x
)))))))
480 ((memq state
'(nil &rest
)) (cl--make-usage-args x
))
481 (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
483 (if (and (consp (car x
)) (eq state
'&key
))
484 (list (caar x
) (cl--make-usage-var (nth 1 (car x
))))
485 (cl--make-usage-var (car x
)))
487 (cl--make-usage-args (nthcdr 2 x
)) ;SVAR.
491 (defun cl--do-&aux
(args)
492 (while (and (eq (car args
) '&aux
) (pop args
))
493 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
494 (if (consp (car args
))
495 (if (and cl--bind-enquote
(cl-cadar args
))
496 (cl--do-arglist (caar args
)
497 `',(cadr (pop args
)))
498 (cl--do-arglist (caar args
) (cadr (pop args
))))
499 (cl--do-arglist (pop args
) nil
))))
500 (if args
(error "Malformed argument list ends with: %S" args
)))
502 (defun cl--do-arglist (args expr
&optional num
) ; uses cl--bind-*
504 (if (or (memq args cl--lambda-list-keywords
) (not (symbolp args
)))
505 (error "Invalid argument name: %s" args
)
506 (push (list args expr
) cl--bind-lets
))
507 (setq args
(cl-copy-list args
))
508 (let ((p (last args
))) (if (cdr p
) (setcdr p
(list '&rest
(cdr p
)))))
509 (let ((p (memq '&body args
))) (if p
(setcar p
'&rest
)))
510 (if (memq '&environment args
) (error "&environment used incorrectly"))
511 (let ((restarg (memq '&rest args
))
512 (safety (if (cl--compiling-file) cl--optimize-safety
3))
514 (laterarg nil
) (exactarg nil
) minarg
)
515 (or num
(setq num
0))
516 (setq restarg
(if (listp (cadr restarg
))
517 (make-symbol "--cl-rest--")
519 (push (list restarg expr
) cl--bind-lets
)
520 (if (eq (car args
) '&whole
)
521 (push (list (cl--pop2 args
) restarg
) cl--bind-lets
))
523 (setq minarg restarg
)
524 (while (and p
(not (memq (car p
) cl--lambda-list-keywords
)))
525 (or (eq p args
) (setq minarg
(list 'cdr minarg
)))
527 (if (memq (car p
) '(nil &aux
))
528 (setq minarg
`(= (length ,restarg
)
529 ,(length (cl-ldiff args p
)))
530 exactarg
(not (eq args p
)))))
531 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
532 (let ((poparg (list (if (or (cdr args
) (not exactarg
)) 'pop
'car
)
536 (if (or laterarg
(= safety
0)) poparg
538 (signal 'wrong-number-of-arguments
539 (list ,(and (not (eq cl--bind-block
'cl-none
))
541 (length ,restarg
)))))))
542 (setq num
(1+ num
) laterarg t
))
543 (while (and (eq (car args
) '&optional
) (pop args
))
544 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
545 (let ((arg (pop args
)))
546 (or (consp arg
) (setq arg
(list arg
)))
547 (if (cddr arg
) (cl--do-arglist (nth 2 arg
) `(and ,restarg t
)))
548 (let ((def (if (cdr arg
) (nth 1 arg
)
549 (or (car cl--bind-defs
)
550 (nth 1 (assq (car arg
) cl--bind-defs
)))))
551 (poparg `(pop ,restarg
)))
552 (and def cl--bind-enquote
(setq def
`',def
))
553 (cl--do-arglist (car arg
)
554 (if def
`(if ,restarg
,poparg
,def
) poparg
))
555 (setq num
(1+ num
))))))
556 (if (eq (car args
) '&rest
)
557 (let ((arg (cl--pop2 args
)))
558 (if (consp arg
) (cl--do-arglist arg restarg
)))
559 (or (eq (car args
) '&key
) (= safety
0) exactarg
561 (signal 'wrong-number-of-arguments
563 ,(and (not (eq cl--bind-block
'cl-none
))
565 (+ ,num
(length ,restarg
)))))
567 (while (and (eq (car args
) '&key
) (pop args
))
568 (while (and args
(not (memq (car args
) cl--lambda-list-keywords
)))
569 (let ((arg (pop args
)))
570 (or (consp arg
) (setq arg
(list arg
)))
571 (let* ((karg (if (consp (car arg
)) (caar arg
)
572 (let ((name (symbol-name (car arg
))))
573 ;; Strip a leading underscore, since it only
574 ;; means that this argument is unused, but
575 ;; shouldn't affect the key's name (bug#12367).
576 (if (eq ?_
(aref name
0))
577 (setq name
(substring name
1)))
578 (intern (format ":%s" name
)))))
579 (varg (if (consp (car arg
)) (cl-cadar arg
) (car arg
)))
580 (def (if (cdr arg
) (cadr arg
)
581 ;; The ordering between those two or clauses is
582 ;; irrelevant, since in practice only one of the two
583 ;; is ever non-nil (the car is only used for
584 ;; cl-deftype which doesn't use the cdr).
585 (or (car cl--bind-defs
)
586 (cadr (assq varg cl--bind-defs
)))))
587 (look `(plist-member ,restarg
',karg
)))
588 (and def cl--bind-enquote
(setq def
`',def
))
590 (let* ((temp (or (nth 2 arg
) (make-symbol "--cl-var--")))
591 (val `(car (cdr ,temp
))))
592 (cl--do-arglist temp look
)
595 (prog1 ,val
(setq ,temp t
))
599 `(car (cdr ,(if (null def
)
602 ,(if (eq (cl--const-expr-p def
) t
)
603 `'(nil ,(cl--const-expr-val def
))
604 `(list nil
,def
))))))))
606 (setq keys
(nreverse keys
))
607 (or (and (eq (car args
) '&allow-other-keys
) (pop args
))
608 (null keys
) (= safety
0)
609 (let* ((var (make-symbol "--cl-keys--"))
610 (allow '(:allow-other-keys
))
613 ((memq (car ,var
) ',(append keys allow
))
614 (setq ,var
(cdr (cdr ,var
))))
615 ((car (cdr (memq (quote ,@allow
) ,restarg
)))
619 ,(format "Keyword argument %%s not one of %s"
622 (push `(let ((,var
,restarg
)) ,check
) cl--bind-forms
)))
626 (defun cl--arglist-args (args)
627 (if (nlistp args
) (list args
)
628 (let ((res nil
) (kind nil
) arg
)
630 (setq arg
(pop args
))
631 (if (memq arg cl--lambda-list-keywords
) (setq kind arg
)
632 (if (eq arg
'&cl-defs
) (pop args
)
633 (and (consp arg
) kind
(setq arg
(car arg
)))
634 (and (consp arg
) (cdr arg
) (eq kind
'&key
) (setq arg
(cadr arg
)))
635 (setq res
(nconc res
(cl--arglist-args arg
))))))
636 (nconc res
(and args
(list args
))))))
639 (defmacro cl-destructuring-bind
(args expr
&rest body
)
640 "Bind the variables in ARGS to the result of EXPR and execute BODY."
642 (debug (&define cl-macro-list def-form cl-declarations def-body
)))
643 (let* ((cl--bind-lets nil
) (cl--bind-forms nil
)
644 (cl--bind-defs nil
) (cl--bind-block 'cl-none
) (cl--bind-enquote nil
))
645 (cl--do-arglist (or args
'(&aux
)) expr
)
646 (macroexp-let* (nreverse cl--bind-lets
)
647 (macroexp-progn (append (nreverse cl--bind-forms
) body
)))))
650 ;;; The `cl-eval-when' form.
652 (defvar cl--not-toplevel nil
)
655 (defmacro cl-eval-when
(when &rest body
)
656 "Control when BODY is evaluated.
657 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
658 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
659 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
661 \(fn (WHEN...) BODY...)"
662 (declare (indent 1) (debug (sexp body
)))
663 (if (and (fboundp 'cl--compiling-file
) (cl--compiling-file)
664 (not cl--not-toplevel
) (not (boundp 'for-effect
))) ;Horrible kludge.
665 (let ((comp (or (memq 'compile when
) (memq :compile-toplevel when
)))
666 (cl--not-toplevel t
))
667 (if (or (memq 'load when
) (memq :load-toplevel when
))
668 (if comp
(cons 'progn
(mapcar 'cl--compile-time-too body
))
669 `(if nil nil
,@body
))
670 (progn (if comp
(eval (cons 'progn body
))) nil
)))
671 (and (or (memq 'eval when
) (memq :execute when
))
672 (cons 'progn body
))))
674 (defun cl--compile-time-too (form)
675 (or (and (symbolp (car-safe form
)) (get (car-safe form
) 'byte-hunk-handler
))
676 (setq form
(macroexpand
677 form
(cons '(cl-eval-when) byte-compile-macro-environment
))))
678 (cond ((eq (car-safe form
) 'progn
)
679 (cons 'progn
(mapcar 'cl--compile-time-too
(cdr form
))))
680 ((eq (car-safe form
) 'cl-eval-when
)
681 (let ((when (nth 1 form
)))
682 (if (or (memq 'eval when
) (memq :execute when
))
683 `(cl-eval-when (compile ,@when
) ,@(cddr form
))
685 (t (eval form
) form
)))
688 (defmacro cl-load-time-value
(form &optional _read-only
)
689 "Like `progn', but evaluates the body at load time.
690 The result of the body appears to the compiler as a quoted constant."
691 (declare (debug (form &optional sexp
)))
692 (if (cl--compiling-file)
693 (let* ((temp (cl-gentemp "--cl-load-time--"))
694 (set `(setq ,temp
,form
)))
695 (if (and (fboundp 'byte-compile-file-form-defmumble
)
696 (boundp 'this-kind
) (boundp 'that-one
))
697 ;; Else, we can't output right away, so we have to delay it to the
698 ;; next time we're at the top-level.
699 ;; FIXME: Use advice-add/remove.
700 (fset 'byte-compile-file-form
701 (let ((old (symbol-function 'byte-compile-file-form
)))
703 (fset 'byte-compile-file-form old
)
704 (byte-compile-file-form set
)
705 (byte-compile-file-form form
))))
706 ;; If we're not in the middle of compiling something, we can
707 ;; output directly to byte-compile-outbuffer, to make sure
708 ;; temp is set before we use it.
709 (print set byte-compile--outbuffer
))
714 ;;; Conditional control structures.
717 (defmacro cl-case
(expr &rest clauses
)
718 "Eval EXPR and choose among clauses on that value.
719 Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
720 against each key in each KEYLIST; the corresponding BODY is evaluated.
721 If no clause succeeds, cl-case returns nil. A single atom may be used in
722 place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
723 allowed only in the final clause, and matches if no other keys match.
724 Key values are compared by `eql'.
725 \n(fn EXPR (KEYLIST BODY...)...)"
726 (declare (indent 1) (debug (form &rest
(sexp body
))))
727 (macroexp-let2 macroexp-copyable-p temp expr
728 (let* ((head-list nil
))
732 (cons (cond ((memq (car c
) '(t otherwise
)) t
)
733 ((eq (car c
) 'cl--ecase-error-flag
)
734 `(error "cl-ecase failed: %s, %s"
735 ,temp
',(reverse head-list
)))
737 (setq head-list
(append (car c
) head-list
))
738 `(cl-member ,temp
',(car c
)))
740 (if (memq (car c
) head-list
)
741 (error "Duplicate key in case: %s"
743 (push (car c
) head-list
)
744 `(eql ,temp
',(car c
))))
745 (or (cdr c
) '(nil))))
749 (defmacro cl-ecase
(expr &rest clauses
)
750 "Like `cl-case', but error if no case fits.
751 `otherwise'-clauses are not allowed.
752 \n(fn EXPR (KEYLIST BODY...)...)"
753 (declare (indent 1) (debug cl-case
))
754 `(cl-case ,expr
,@clauses
(cl--ecase-error-flag)))
757 (defmacro cl-typecase
(expr &rest clauses
)
758 "Evals EXPR, chooses among clauses on that value.
759 Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
760 satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
761 cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
762 final clause, and matches if no other keys match.
763 \n(fn EXPR (TYPE BODY...)...)"
765 (debug (form &rest
([&or cl-type-spec
"otherwise"] body
))))
766 (macroexp-let2 macroexp-copyable-p temp expr
767 (let* ((type-list nil
))
773 (cons (cond ((eq (car c
) 'otherwise
) t
)
774 ((eq (car c
) 'cl--ecase-error-flag
)
775 `(error "cl-etypecase failed: %s, %s"
776 ,temp
',(reverse type-list
)))
778 (push (car c
) type-list
)
779 `(cl-typep ,temp
',(car c
))))
780 (or (cdr c
) '(nil)))))
784 (defmacro cl-etypecase
(expr &rest clauses
)
785 "Like `cl-typecase', but error if no case fits.
786 `otherwise'-clauses are not allowed.
787 \n(fn EXPR (TYPE BODY...)...)"
788 (declare (indent 1) (debug cl-typecase
))
789 `(cl-typecase ,expr
,@clauses
(cl--ecase-error-flag)))
792 ;;; Blocks and exits.
795 (defmacro cl-block
(name &rest body
)
796 "Define a lexically-scoped block named NAME.
797 NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
798 to jump prematurely out of the block. This differs from `catch' and `throw'
799 in two respects: First, the NAME is an unevaluated symbol rather than a
800 quoted symbol or other form; and second, NAME is lexically rather than
801 dynamically scoped: Only references to it within BODY will work. These
802 references may appear inside macro expansions, but not inside functions
804 (declare (indent 1) (debug (symbolp body
)))
805 (if (cl--safe-expr-p `(progn ,@body
)) `(progn ,@body
)
807 (catch ',(intern (format "--cl-block-%s--" name
))
811 (defmacro cl-return
(&optional result
)
812 "Return from the block named nil.
813 This is equivalent to `(cl-return-from nil RESULT)'."
814 (declare (debug (&optional form
)))
815 `(cl-return-from nil
,result
))
818 (defmacro cl-return-from
(name &optional result
)
819 "Return from the block named NAME.
820 This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
821 returning RESULT from that form (or nil if RESULT is omitted).
822 This is compatible with Common Lisp, but note that `defun' and
823 `defmacro' do not create implicit blocks as they do in Common Lisp."
824 (declare (indent 1) (debug (symbolp &optional form
)))
825 (let ((name2 (intern (format "--cl-block-%s--" name
))))
826 `(cl--block-throw ',name2
,result
)))
829 ;;; The "cl-loop" macro.
831 (defvar cl--loop-args
) (defvar cl--loop-accum-var
) (defvar cl--loop-accum-vars
)
832 (defvar cl--loop-bindings
) (defvar cl--loop-body
)
833 (defvar cl--loop-finally
)
834 (defvar cl--loop-finish-flag
) ;Symbol set to nil to exit the loop?
835 (defvar cl--loop-first-flag
)
836 (defvar cl--loop-initially
) (defvar cl--loop-iterator-function
)
837 (defvar cl--loop-name
)
838 (defvar cl--loop-result
) (defvar cl--loop-result-explicit
)
839 (defvar cl--loop-result-var
) (defvar cl--loop-steps
)
840 (defvar cl--loop-symbol-macs
)
842 (defun cl--loop-set-iterator-function (kind iterator
)
843 (if cl--loop-iterator-function
844 ;; FIXME: Of course, we could make it work, but why bother.
845 (error "Iteration on %S does not support this combination" kind
)
846 (setq cl--loop-iterator-function iterator
)))
849 (defmacro cl-loop
(&rest loop-args
)
850 "The Common Lisp `loop' macro.
851 Valid clauses include:
853 for VAR from/upfrom/downfrom EXPR1 to/upto/downto/above/below EXPR2 by EXPR3
854 for VAR = EXPR1 then EXPR2
855 for VAR in/on/in-ref LIST by FUNC
856 for VAR across/across-ref ARRAY
858 the elements of/of-ref SEQUENCE [using (index VAR2)]
859 the symbols [of OBARRAY]
860 the hash-keys/hash-values of HASH-TABLE [using (hash-values/hash-keys V2)]
861 the key-codes/key-bindings/key-seqs of KEYMAP [using (key-bindings VAR2)]
862 the overlays/intervals [of BUFFER] [from POS1] [to POS2]
864 the windows [of FRAME]
867 while/until/always/never/thereis CONDITION
868 Accumulation clauses:
869 collect/append/nconc/concat/vconcat/count/sum/maximize/minimize FORM
871 Miscellaneous clauses:
873 if/when/unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...]
875 initially/finally [do] EXPRS...
877 [finally] return EXPR
879 For more details, see Info node `(cl)Loop Facility'.
882 (declare (debug (&rest
&or
883 ;; These are usually followed by a symbol, but it can
884 ;; actually be any destructuring-bind pattern, which
885 ;; would erroneously match `form'.
886 [[&or
"for" "as" "with" "and"] sexp
]
887 ;; These are followed by expressions which could
888 ;; erroneously match `symbolp'.
889 [[&or
"from" "upfrom" "downfrom" "to" "upto" "downto"
890 "above" "below" "by" "in" "on" "=" "across"
891 "repeat" "while" "until" "always" "never"
892 "thereis" "collect" "append" "nconc" "sum"
893 "count" "maximize" "minimize" "if" "unless"
896 ;; Simple default, which covers 99% of the cases.
898 (if (not (memq t
(mapcar #'symbolp
899 (delq nil
(delq t
(cl-copy-list loop-args
))))))
900 `(cl-block nil
(while t
,@loop-args
))
901 (let ((cl--loop-args loop-args
) (cl--loop-name nil
) (cl--loop-bindings nil
)
902 (cl--loop-body nil
) (cl--loop-steps nil
)
903 (cl--loop-result nil
) (cl--loop-result-explicit nil
)
904 (cl--loop-result-var nil
) (cl--loop-finish-flag nil
)
905 (cl--loop-accum-var nil
) (cl--loop-accum-vars nil
)
906 (cl--loop-initially nil
) (cl--loop-finally nil
)
907 (cl--loop-iterator-function nil
) (cl--loop-first-flag nil
)
908 (cl--loop-symbol-macs nil
))
909 ;; Here is more or less how those dynbind vars are used after looping
910 ;; over cl--parse-loop-clause:
912 ;; (cl-block ,cl--loop-name
913 ;; (cl-symbol-macrolet ,cl--loop-symbol-macs
914 ;; (foldl #'cl--loop-let
915 ;; `((,cl--loop-result-var)
916 ;; ((,cl--loop-first-flag t))
917 ;; ((,cl--loop-finish-flag t))
918 ;; ,@cl--loop-bindings)
919 ;; ,@(nreverse cl--loop-initially)
920 ;; (while ;(well: cl--loop-iterator-function)
921 ;; ,(car (cl--loop-build-ands (nreverse cl--loop-body)))
922 ;; ,@(cadr (cl--loop-build-ands (nreverse cl--loop-body)))
923 ;; ,@(nreverse cl--loop-steps)
924 ;; (setq ,cl--loop-first-flag nil))
925 ;; (if (not ,cl--loop-finish-flag) ;FIXME: Why `if' vs `progn'?
926 ;; ,cl--loop-result-var
927 ;; ,@(nreverse cl--loop-finally)
928 ;; ,(or cl--loop-result-explicit
929 ;; cl--loop-result)))))
931 (setq cl--loop-args
(append cl--loop-args
'(cl-end-loop)))
932 (while (not (eq (car cl--loop-args
) 'cl-end-loop
))
933 (cl--parse-loop-clause))
934 (if cl--loop-finish-flag
935 (push `((,cl--loop-finish-flag t
)) cl--loop-bindings
))
936 (if cl--loop-first-flag
937 (progn (push `((,cl--loop-first-flag t
)) cl--loop-bindings
)
938 (push `(setq ,cl--loop-first-flag nil
) cl--loop-steps
)))
939 (let* ((epilogue (nconc (nreverse cl--loop-finally
)
940 (list (or cl--loop-result-explicit
942 (ands (cl--loop-build-ands (nreverse cl--loop-body
)))
943 (while-body (nconc (cadr ands
) (nreverse cl--loop-steps
)))
945 (nreverse cl--loop-initially
)
946 (list (if cl--loop-iterator-function
947 `(cl-block --cl-finish--
948 ,(funcall cl--loop-iterator-function
949 (if (eq (car ands
) t
) while-body
950 (cons `(or ,(car ands
)
955 `(while ,(car ands
) ,@while-body
)))
956 (if cl--loop-finish-flag
957 (if (equal epilogue
'(nil)) (list cl--loop-result-var
)
958 `((if ,cl--loop-finish-flag
959 (progn ,@epilogue
) ,cl--loop-result-var
)))
961 (if cl--loop-result-var
962 (push (list cl--loop-result-var
) cl--loop-bindings
))
963 (while cl--loop-bindings
964 (if (cdar cl--loop-bindings
)
965 (setq body
(list (cl--loop-let (pop cl--loop-bindings
) body t
)))
967 (while (and cl--loop-bindings
968 (not (cdar cl--loop-bindings
)))
969 (push (car (pop cl--loop-bindings
)) lets
))
970 (setq body
(list (cl--loop-let lets body nil
))))))
971 (if cl--loop-symbol-macs
973 (list `(cl-symbol-macrolet ,cl--loop-symbol-macs
,@body
))))
974 `(cl-block ,cl--loop-name
,@body
)))))
976 ;; Below is a complete spec for cl-loop, in several parts that correspond
977 ;; to the syntax given in CLtL2. The specs do more than specify where
978 ;; the forms are; it also specifies, as much as Edebug allows, all the
979 ;; syntactically valid cl-loop clauses. The disadvantage of this
980 ;; completeness is rigidity, but the "for ... being" clause allows
981 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
983 ;; (def-edebug-spec cl-loop
984 ;; ([&optional ["named" symbolp]]
990 ;; loop-initial-final]
991 ;; [&rest loop-clause]
994 ;; (def-edebug-spec loop-with
997 ;; [&optional ["=" form]]
998 ;; &rest ["and" loop-var
1000 ;; [&optional ["=" form]]]))
1002 ;; (def-edebug-spec loop-for-as
1003 ;; ([&or "for" "as"] loop-for-as-subclause
1004 ;; &rest ["and" loop-for-as-subclause]))
1006 ;; (def-edebug-spec loop-for-as-subclause
1010 ;; [[&or "in" "on" "in-ref" "across-ref"]
1011 ;; form &optional ["by" function-form]]
1013 ;; ["=" form &optional ["then" form]]
1016 ;; [&or "the" "each"]
1018 ;; [[&or "element" "elements"]
1019 ;; [&or "of" "in" "of-ref"] form
1020 ;; &optional "using" ["index" symbolp]];; is this right?
1021 ;; [[&or "hash-key" "hash-keys"
1022 ;; "hash-value" "hash-values"]
1024 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
1025 ;; "hash-key" "hash-keys"] sexp)]]
1027 ;; [[&or "symbol" "present-symbol" "external-symbol"
1028 ;; "symbols" "present-symbols" "external-symbols"]
1029 ;; [&or "in" "of"] package-p]
1031 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
1032 ;; [[&or "frame" "frames"
1033 ;; "screen" "screens"
1034 ;; "buffer" "buffers"]]
1036 ;; [[&or "window" "windows"]
1037 ;; [&or "of" "in"] form]
1039 ;; [[&or "overlay" "overlays"
1040 ;; "extent" "extents"]
1041 ;; [&or "of" "in"] form
1042 ;; &optional [[&or "from" "to"] form]]
1044 ;; [[&or "interval" "intervals"]
1045 ;; [&or "in" "of"] form
1046 ;; &optional [[&or "from" "to"] form]
1047 ;; ["property" form]]
1049 ;; [[&or "key-code" "key-codes"
1050 ;; "key-seq" "key-seqs"
1051 ;; "key-binding" "key-bindings"]
1052 ;; [&or "in" "of"] form
1053 ;; &optional ["using" ([&or "key-code" "key-codes"
1054 ;; "key-seq" "key-seqs"
1055 ;; "key-binding" "key-bindings"]
1057 ;; ;; For arbitrary extensions, recognize anything else.
1058 ;; [symbolp &rest &or symbolp form]
1061 ;; ;; arithmetic - must be last since all parts are optional.
1062 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
1063 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
1064 ;; [&optional ["by" form]]
1067 ;; (def-edebug-spec loop-initial-final
1068 ;; (&or ["initially"
1069 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
1070 ;; &rest loop-non-atomic-expr]
1072 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
1073 ;; ["return" form]]))
1075 ;; (def-edebug-spec loop-and-clause
1076 ;; (loop-clause &rest ["and" loop-clause]))
1078 ;; (def-edebug-spec loop-clause
1080 ;; [[&or "while" "until" "always" "never" "thereis"] form]
1082 ;; [[&or "collect" "collecting"
1083 ;; "append" "appending"
1084 ;; "nconc" "nconcing"
1085 ;; "concat" "vconcat"] form
1086 ;; [&optional ["into" loop-var]]]
1088 ;; [[&or "count" "counting"
1090 ;; "maximize" "maximizing"
1091 ;; "minimize" "minimizing"] form
1092 ;; [&optional ["into" loop-var]]
1095 ;; [[&or "if" "when" "unless"]
1096 ;; form loop-and-clause
1097 ;; [&optional ["else" loop-and-clause]]
1098 ;; [&optional "end"]]
1100 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
1103 ;; loop-initial-final
1106 ;; (def-edebug-spec loop-non-atomic-expr
1107 ;; ([¬ atom] form))
1109 ;; (def-edebug-spec loop-var
1110 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
1112 ;; ;; (loop-var . [&or nil loop-var])
1113 ;; ;; (symbolp . [&or nil loop-var])
1114 ;; ;; (symbolp . loop-var)
1115 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
1116 ;; ;; (symbolp . (symbolp . loop-var))
1117 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
1118 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
1120 ;; (def-edebug-spec loop-type-spec
1121 ;; (&optional ["of-type" loop-d-type-spec]))
1123 ;; (def-edebug-spec loop-d-type-spec
1124 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
1128 (defun cl--parse-loop-clause () ; uses loop-*
1129 (let ((word (pop cl--loop-args
))
1130 (hash-types '(hash-key hash-keys hash-value hash-values
))
1131 (key-types '(key-code key-codes key-seq key-seqs
1132 key-binding key-bindings
)))
1135 ((null cl--loop-args
)
1136 (error "Malformed `cl-loop' macro"))
1139 (setq cl--loop-name
(pop cl--loop-args
)))
1141 ((eq word
'initially
)
1142 (if (memq (car cl--loop-args
) '(do doing
)) (pop cl--loop-args
))
1143 (or (consp (car cl--loop-args
))
1144 (error "Syntax error on `initially' clause"))
1145 (while (consp (car cl--loop-args
))
1146 (push (pop cl--loop-args
) cl--loop-initially
)))
1149 (if (eq (car cl--loop-args
) 'return
)
1150 (setq cl--loop-result-explicit
1151 (or (cl--pop2 cl--loop-args
) '(quote nil
)))
1152 (if (memq (car cl--loop-args
) '(do doing
)) (pop cl--loop-args
))
1153 (or (consp (car cl--loop-args
))
1154 (error "Syntax error on `finally' clause"))
1155 (if (and (eq (caar cl--loop-args
) 'return
) (null cl--loop-name
))
1156 (setq cl--loop-result-explicit
1157 (or (nth 1 (pop cl--loop-args
)) '(quote nil
)))
1158 (while (consp (car cl--loop-args
))
1159 (push (pop cl--loop-args
) cl--loop-finally
)))))
1161 ((memq word
'(for as
))
1162 (let ((loop-for-bindings nil
) (loop-for-sets nil
) (loop-for-steps nil
)
1165 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1166 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
1167 ;; these vars get added to the macro-environment.
1168 (let ((var (or (pop cl--loop-args
) (cl-gensym "--cl-var--"))))
1169 (setq word
(pop cl--loop-args
))
1170 (if (eq word
'being
) (setq word
(pop cl--loop-args
)))
1171 (if (memq word
'(the each
)) (setq word
(pop cl--loop-args
)))
1172 (if (memq word
'(buffer buffers
))
1174 cl--loop-args
(cons '(buffer-list) cl--loop-args
)))
1177 ((memq word
'(from downfrom upfrom to downto upto
1179 (push word cl--loop-args
)
1180 (if (memq (car cl--loop-args
) '(downto above
))
1181 (error "Must specify `from' value for downward cl-loop"))
1182 (let* ((down (or (eq (car cl--loop-args
) 'downfrom
)
1183 (memq (nth 2 cl--loop-args
)
1185 (excl (or (memq (car cl--loop-args
) '(above below
))
1186 (memq (nth 2 cl--loop-args
)
1188 (start (and (memq (car cl--loop-args
)
1189 '(from upfrom downfrom
))
1190 (cl--pop2 cl--loop-args
)))
1191 (end (and (memq (car cl--loop-args
)
1192 '(to upto downto above below
))
1193 (cl--pop2 cl--loop-args
)))
1194 (step (and (eq (car cl--loop-args
) 'by
)
1195 (cl--pop2 cl--loop-args
)))
1196 (end-var (and (not (macroexp-const-p end
))
1197 (make-symbol "--cl-var--")))
1198 (step-var (and (not (macroexp-const-p step
))
1199 (make-symbol "--cl-var--"))))
1200 (and step
(numberp step
) (<= step
0)
1201 (error "Loop `by' value is not positive: %s" step
))
1202 (push (list var
(or start
0)) loop-for-bindings
)
1203 (if end-var
(push (list end-var end
) loop-for-bindings
))
1204 (if step-var
(push (list step-var step
)
1208 (if down
(if excl
'> '>=) (if excl
'< '<=))
1209 var
(or end-var end
))
1211 (push (list var
(list (if down
'-
'+) var
1212 (or step-var step
1)))
1215 ((memq word
'(in in-ref on
))
1216 (let* ((on (eq word
'on
))
1217 (temp (if (and on
(symbolp var
))
1218 var
(make-symbol "--cl-var--"))))
1219 (push (list temp
(pop cl--loop-args
)) loop-for-bindings
)
1220 (push `(consp ,temp
) cl--loop-body
)
1221 (if (eq word
'in-ref
)
1222 (push (list var
`(car ,temp
)) cl--loop-symbol-macs
)
1225 (push (list var nil
) loop-for-bindings
)
1226 (push (list var
(if on temp
`(car ,temp
)))
1229 (if (eq (car cl--loop-args
) 'by
)
1230 (let ((step (cl--pop2 cl--loop-args
)))
1231 (if (and (memq (car-safe step
)
1234 (symbolp (nth 1 step
)))
1235 (list (nth 1 step
) temp
)
1236 `(funcall ,step
,temp
)))
1241 (let* ((start (pop cl--loop-args
))
1242 (then (if (eq (car cl--loop-args
) 'then
)
1243 (cl--pop2 cl--loop-args
) start
)))
1244 (push (list var nil
) loop-for-bindings
)
1245 (if (or ands
(eq (car cl--loop-args
) 'and
))
1248 (if ,(or cl--loop-first-flag
1249 (setq cl--loop-first-flag
1250 (make-symbol "--cl-var--")))
1253 (push (list var then
) loop-for-steps
))
1255 (if (eq start then
) start
1256 `(if ,(or cl--loop-first-flag
1257 (setq cl--loop-first-flag
1258 (make-symbol "--cl-var--")))
1262 ((memq word
'(across across-ref
))
1263 (let ((temp-vec (make-symbol "--cl-vec--"))
1264 (temp-idx (make-symbol "--cl-idx--")))
1265 (push (list temp-vec
(pop cl--loop-args
)) loop-for-bindings
)
1266 (push (list temp-idx -
1) loop-for-bindings
)
1267 (push `(< (setq ,temp-idx
(1+ ,temp-idx
))
1270 (if (eq word
'across-ref
)
1271 (push (list var
`(aref ,temp-vec
,temp-idx
))
1272 cl--loop-symbol-macs
)
1273 (push (list var nil
) loop-for-bindings
)
1274 (push (list var
`(aref ,temp-vec
,temp-idx
))
1277 ((memq word
'(element elements
))
1278 (let ((ref (or (memq (car cl--loop-args
) '(in-ref of-ref
))
1279 (and (not (memq (car cl--loop-args
) '(in of
)))
1280 (error "Expected `of'"))))
1281 (seq (cl--pop2 cl--loop-args
))
1282 (temp-seq (make-symbol "--cl-seq--"))
1284 (if (eq (car cl--loop-args
) 'using
)
1285 (if (and (= (length (cadr cl--loop-args
)) 2)
1286 (eq (cl-caadr cl--loop-args
) 'index
))
1287 (cadr (cl--pop2 cl--loop-args
))
1288 (error "Bad `using' clause"))
1289 (make-symbol "--cl-idx--"))))
1290 (push (list temp-seq seq
) loop-for-bindings
)
1291 (push (list temp-idx
0) loop-for-bindings
)
1293 (let ((temp-len (make-symbol "--cl-len--")))
1294 (push (list temp-len
`(length ,temp-seq
))
1296 (push (list var
`(elt ,temp-seq
,temp-idx
))
1297 cl--loop-symbol-macs
)
1298 (push `(< ,temp-idx
,temp-len
) cl--loop-body
))
1299 (push (list var nil
) loop-for-bindings
)
1300 (push `(and ,temp-seq
1301 (or (consp ,temp-seq
)
1302 (< ,temp-idx
(length ,temp-seq
))))
1304 (push (list var
`(if (consp ,temp-seq
)
1306 (aref ,temp-seq
,temp-idx
)))
1308 (push (list temp-idx
`(1+ ,temp-idx
))
1311 ((memq word hash-types
)
1312 (or (memq (car cl--loop-args
) '(in of
))
1313 (error "Expected `of'"))
1314 (let* ((table (cl--pop2 cl--loop-args
))
1316 (if (eq (car cl--loop-args
) 'using
)
1317 (if (and (= (length (cadr cl--loop-args
)) 2)
1318 (memq (cl-caadr cl--loop-args
) hash-types
)
1319 (not (eq (cl-caadr cl--loop-args
) word
)))
1320 (cadr (cl--pop2 cl--loop-args
))
1321 (error "Bad `using' clause"))
1322 (make-symbol "--cl-var--"))))
1323 (if (memq word
'(hash-value hash-values
))
1324 (setq var
(prog1 other
(setq other var
))))
1325 (cl--loop-set-iterator-function
1326 'hash-tables
(lambda (body)
1327 `(maphash (lambda (,var
,other
) .
,body
)
1330 ((memq word
'(symbol present-symbol external-symbol
1331 symbols present-symbols external-symbols
))
1332 (let ((ob (and (memq (car cl--loop-args
) '(in of
))
1333 (cl--pop2 cl--loop-args
))))
1334 (cl--loop-set-iterator-function
1335 'symbols
(lambda (body)
1336 `(mapatoms (lambda (,var
) .
,body
) ,ob
)))))
1338 ((memq word
'(overlay overlays extent extents
))
1339 (let ((buf nil
) (from nil
) (to nil
))
1340 (while (memq (car cl--loop-args
) '(in of from to
))
1341 (cond ((eq (car cl--loop-args
) 'from
)
1342 (setq from
(cl--pop2 cl--loop-args
)))
1343 ((eq (car cl--loop-args
) 'to
)
1344 (setq to
(cl--pop2 cl--loop-args
)))
1345 (t (setq buf
(cl--pop2 cl--loop-args
)))))
1346 (cl--loop-set-iterator-function
1347 'overlays
(lambda (body)
1349 (lambda (,var
,(make-symbol "--cl-var--"))
1350 (progn .
,body
) nil
)
1353 ((memq word
'(interval intervals
))
1354 (let ((buf nil
) (prop nil
) (from nil
) (to nil
)
1355 (var1 (make-symbol "--cl-var1--"))
1356 (var2 (make-symbol "--cl-var2--")))
1357 (while (memq (car cl--loop-args
) '(in of property from to
))
1358 (cond ((eq (car cl--loop-args
) 'from
)
1359 (setq from
(cl--pop2 cl--loop-args
)))
1360 ((eq (car cl--loop-args
) 'to
)
1361 (setq to
(cl--pop2 cl--loop-args
)))
1362 ((eq (car cl--loop-args
) 'property
)
1363 (setq prop
(cl--pop2 cl--loop-args
)))
1364 (t (setq buf
(cl--pop2 cl--loop-args
)))))
1365 (if (and (consp var
) (symbolp (car var
)) (symbolp (cdr var
)))
1366 (setq var1
(car var
) var2
(cdr var
))
1367 (push (list var
`(cons ,var1
,var2
)) loop-for-sets
))
1368 (cl--loop-set-iterator-function
1369 'intervals
(lambda (body)
1371 (lambda (,var1
,var2
) .
,body
)
1372 ,buf
,prop
,from
,to
)))))
1374 ((memq word key-types
)
1375 (or (memq (car cl--loop-args
) '(in of
))
1376 (error "Expected `of'"))
1377 (let ((cl-map (cl--pop2 cl--loop-args
))
1379 (if (eq (car cl--loop-args
) 'using
)
1380 (if (and (= (length (cadr cl--loop-args
)) 2)
1381 (memq (cl-caadr cl--loop-args
) key-types
)
1382 (not (eq (cl-caadr cl--loop-args
) word
)))
1383 (cadr (cl--pop2 cl--loop-args
))
1384 (error "Bad `using' clause"))
1385 (make-symbol "--cl-var--"))))
1386 (if (memq word
'(key-binding key-bindings
))
1387 (setq var
(prog1 other
(setq other var
))))
1388 (cl--loop-set-iterator-function
1389 'keys
(lambda (body)
1390 `(,(if (memq word
'(key-seq key-seqs
))
1391 'cl--map-keymap-recursively
'map-keymap
)
1392 (lambda (,var
,other
) .
,body
) ,cl-map
)))))
1394 ((memq word
'(frame frames screen screens
))
1395 (let ((temp (make-symbol "--cl-var--")))
1396 (push (list var
'(selected-frame))
1398 (push (list temp nil
) loop-for-bindings
)
1399 (push `(prog1 (not (eq ,var
,temp
))
1400 (or ,temp
(setq ,temp
,var
)))
1402 (push (list var
`(next-frame ,var
))
1405 ((memq word
'(window windows
))
1406 (let ((scr (and (memq (car cl--loop-args
) '(in of
))
1407 (cl--pop2 cl--loop-args
)))
1408 (temp (make-symbol "--cl-var--"))
1409 (minip (make-symbol "--cl-minip--")))
1410 (push (list var
(if scr
1411 `(frame-selected-window ,scr
)
1412 '(selected-window)))
1414 ;; If we started in the minibuffer, we need to
1415 ;; ensure that next-window will bring us back there
1416 ;; at some point. (Bug#7492).
1417 ;; (Consider using walk-windows instead of cl-loop if
1418 ;; you care about such things.)
1419 (push (list minip
`(minibufferp (window-buffer ,var
)))
1421 (push (list temp nil
) loop-for-bindings
)
1422 (push `(prog1 (not (eq ,var
,temp
))
1423 (or ,temp
(setq ,temp
,var
)))
1425 (push (list var
`(next-window ,var
,minip
))
1429 ;; This is an advertised interface: (info "(cl)Other Clauses").
1430 (let ((handler (and (symbolp word
)
1431 (get word
'cl-loop-for-handler
))))
1433 (funcall handler var
)
1434 (error "Expected a `for' preposition, found %s" word
)))))
1435 (eq (car cl--loop-args
) 'and
))
1437 (pop cl--loop-args
))
1438 (if (and ands loop-for-bindings
)
1439 (push (nreverse loop-for-bindings
) cl--loop-bindings
)
1440 (setq cl--loop-bindings
(nconc (mapcar 'list loop-for-bindings
)
1441 cl--loop-bindings
)))
1444 ,(cl--loop-let (nreverse loop-for-sets
) 'setq ands
)
1448 (push (cons (if ands
'cl-psetq
'setq
)
1449 (apply 'append
(nreverse loop-for-steps
)))
1453 (let ((temp (make-symbol "--cl-var--")))
1454 (push (list (list temp
(pop cl--loop-args
))) cl--loop-bindings
)
1455 (push `(>= (setq ,temp
(1- ,temp
)) 0) cl--loop-body
)))
1457 ((memq word
'(collect collecting
))
1458 (let ((what (pop cl--loop-args
))
1459 (var (cl--loop-handle-accum nil
'nreverse
)))
1460 (if (eq var cl--loop-accum-var
)
1461 (push `(progn (push ,what
,var
) t
) cl--loop-body
)
1463 (setq ,var
(nconc ,var
(list ,what
)))
1467 ((memq word
'(nconc nconcing append appending
))
1468 (let ((what (pop cl--loop-args
))
1469 (var (cl--loop-handle-accum nil
'nreverse
)))
1472 ,(if (eq var cl--loop-accum-var
)
1474 (,(if (memq word
'(nconc nconcing
))
1475 #'nreverse
#'reverse
)
1478 `(,(if (memq word
'(nconc nconcing
))
1484 ((memq word
'(concat concating
))
1485 (let ((what (pop cl--loop-args
))
1486 (var (cl--loop-handle-accum "")))
1487 (push `(progn (cl-callf concat
,var
,what
) t
) cl--loop-body
)))
1489 ((memq word
'(vconcat vconcating
))
1490 (let ((what (pop cl--loop-args
))
1491 (var (cl--loop-handle-accum [])))
1492 (push `(progn (cl-callf vconcat
,var
,what
) t
) cl--loop-body
)))
1494 ((memq word
'(sum summing
))
1495 (let ((what (pop cl--loop-args
))
1496 (var (cl--loop-handle-accum 0)))
1497 (push `(progn (cl-incf ,var
,what
) t
) cl--loop-body
)))
1499 ((memq word
'(count counting
))
1500 (let ((what (pop cl--loop-args
))
1501 (var (cl--loop-handle-accum 0)))
1502 (push `(progn (if ,what
(cl-incf ,var
)) t
) cl--loop-body
)))
1504 ((memq word
'(minimize minimizing maximize maximizing
))
1505 (push `(progn ,(macroexp-let2 macroexp-copyable-p temp
1507 (let* ((var (cl--loop-handle-accum nil
))
1508 (func (intern (substring (symbol-name word
)
1510 `(setq ,var
(if ,var
(,func
,var
,temp
) ,temp
))))
1515 (let ((bindings nil
))
1516 (while (progn (push (list (pop cl--loop-args
)
1517 (and (eq (car cl--loop-args
) '=)
1518 (cl--pop2 cl--loop-args
)))
1520 (eq (car cl--loop-args
) 'and
))
1521 (pop cl--loop-args
))
1522 (push (nreverse bindings
) cl--loop-bindings
)))
1525 (push (pop cl--loop-args
) cl--loop-body
))
1528 (push `(not ,(pop cl--loop-args
)) cl--loop-body
))
1531 (or cl--loop-finish-flag
1532 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1533 (push `(setq ,cl--loop-finish-flag
,(pop cl--loop-args
)) cl--loop-body
)
1534 (setq cl--loop-result t
))
1537 (or cl--loop-finish-flag
1538 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1539 (push `(setq ,cl--loop-finish-flag
(not ,(pop cl--loop-args
)))
1541 (setq cl--loop-result t
))
1544 (or cl--loop-finish-flag
1545 (setq cl--loop-finish-flag
(make-symbol "--cl-flag--")))
1546 (or cl--loop-result-var
1547 (setq cl--loop-result-var
(make-symbol "--cl-var--")))
1548 (push `(setq ,cl--loop-finish-flag
1549 (not (setq ,cl--loop-result-var
,(pop cl--loop-args
))))
1552 ((memq word
'(if when unless
))
1553 (let* ((cond (pop cl--loop-args
))
1554 (then (let ((cl--loop-body nil
))
1555 (cl--parse-loop-clause)
1556 (cl--loop-build-ands (nreverse cl--loop-body
))))
1557 (else (let ((cl--loop-body nil
))
1558 (if (eq (car cl--loop-args
) 'else
)
1559 (progn (pop cl--loop-args
) (cl--parse-loop-clause)))
1560 (cl--loop-build-ands (nreverse cl--loop-body
))))
1561 (simple (and (eq (car then
) t
) (eq (car else
) t
))))
1562 (if (eq (car cl--loop-args
) 'end
) (pop cl--loop-args
))
1563 (if (eq word
'unless
) (setq then
(prog1 else
(setq else then
))))
1564 (let ((form (cons (if simple
(cons 'progn
(nth 1 then
)) (nth 2 then
))
1565 (if simple
(nth 1 else
) (list (nth 2 else
))))))
1566 (setq form
(if (cl--expr-contains form
'it
)
1567 `(let ((it ,cond
)) (if it
,@form
))
1568 `(if ,cond
,@form
)))
1569 (push (if simple
`(progn ,form t
) form
) cl--loop-body
))))
1571 ((memq word
'(do doing
))
1573 (or (consp (car cl--loop-args
)) (error "Syntax error on `do' clause"))
1574 (while (consp (car cl--loop-args
)) (push (pop cl--loop-args
) body
))
1575 (push (cons 'progn
(nreverse (cons t body
))) cl--loop-body
)))
1578 (or cl--loop-finish-flag
1579 (setq cl--loop-finish-flag
(make-symbol "--cl-var--")))
1580 (or cl--loop-result-var
1581 (setq cl--loop-result-var
(make-symbol "--cl-var--")))
1582 (push `(setq ,cl--loop-result-var
,(pop cl--loop-args
)
1583 ,cl--loop-finish-flag nil
)
1587 ;; This is an advertised interface: (info "(cl)Other Clauses").
1588 (let ((handler (and (symbolp word
) (get word
'cl-loop-handler
))))
1589 (or handler
(error "Expected a cl-loop keyword, found %s" word
))
1590 (funcall handler
))))
1591 (if (eq (car cl--loop-args
) 'and
)
1592 (progn (pop cl--loop-args
) (cl--parse-loop-clause)))))
1594 (defun cl--unused-var-p (sym)
1595 (or (null sym
) (eq ?_
(aref (symbol-name sym
) 0))))
1597 (defun cl--loop-let (specs body par
) ; modifies cl--loop-bindings
1598 "Build an expression equivalent to (let SPECS BODY).
1599 SPECS can include bindings using `cl-loop's destructuring (not to be
1600 confused with the patterns of `cl-destructuring-bind').
1601 If PAR is nil, do the bindings step by step, like `let*'.
1602 If BODY is `setq', then use SPECS for assignments rather than for bindings."
1603 (let ((temps nil
) (new nil
))
1606 (while (and p
(or (symbolp (car-safe (car p
))) (null (cl-cadar p
))))
1610 (dolist (spec specs
)
1611 (or (macroexp-const-p (cadr spec
))
1612 (let ((temp (make-symbol "--cl-var--")))
1613 (push (list temp
(cadr spec
)) temps
)
1614 (setcar (cdr spec
) temp
)))))))
1616 (let* ((binding (pop specs
))
1617 (spec (car-safe binding
)))
1618 (if (and (consp binding
) (or (consp spec
) (cl--unused-var-p spec
)))
1620 (expr (car (cdr-safe binding
)))
1621 (temp (last spec
0)))
1622 (if (and (cl--unused-var-p temp
) (null expr
))
1623 nil
;; Don't bother declaring/setting `temp' since it won't
1624 ;; be used when `expr' is nil, anyway.
1625 (when (or (null temp
)
1626 (and (eq body
'setq
) (cl--unused-var-p temp
)))
1627 ;; Prefer a fresh uninterned symbol over "_to", to avoid
1628 ;; warnings that we set an unused variable.
1629 (setq temp
(make-symbol "--cl-var--"))
1630 ;; Make sure this temp variable is locally declared.
1631 (when (eq body
'setq
)
1632 (push (list (list temp
)) cl--loop-bindings
)))
1633 (push (list temp expr
) new
))
1635 (push (list (pop spec
)
1636 (and expr
(list (if spec
'pop
'car
) temp
)))
1638 (setq specs
(nconc (nreverse nspecs
) specs
)))
1639 (push binding new
))))
1641 (let ((set (cons (if par
'cl-psetq
'setq
)
1642 (apply 'nconc
(nreverse new
)))))
1643 (if temps
`(let* ,(nreverse temps
) ,set
) set
))
1644 `(,(if par
'let
'let
*)
1645 ,(nconc (nreverse temps
) (nreverse new
)) ,@body
))))
1647 (defun cl--loop-handle-accum (def &optional func
) ; uses loop-*
1648 (if (eq (car cl--loop-args
) 'into
)
1649 (let ((var (cl--pop2 cl--loop-args
)))
1650 (or (memq var cl--loop-accum-vars
)
1651 (progn (push (list (list var def
)) cl--loop-bindings
)
1652 (push var cl--loop-accum-vars
)))
1654 (or cl--loop-accum-var
1657 (setq cl--loop-accum-var
(make-symbol "--cl-var--"))
1660 (setq cl--loop-result
(if func
(list func cl--loop-accum-var
)
1661 cl--loop-accum-var
))
1662 cl--loop-accum-var
))))
1664 (defun cl--loop-build-ands (clauses)
1665 "Return various representations of (and . CLAUSES).
1666 CLAUSES is a list of Elisp expressions, where clauses of the form
1667 \(progn E1 E2 E3 .. t) are the focus of particular optimizations.
1668 The return value has shape (COND BODY COMBO)
1669 such that COMBO is equivalent to (and . CLAUSES)."
1672 ;; Look through `clauses', trying to optimize (progn ,@A t) (progn ,@B) ,@C
1673 ;; into (progn ,@A ,@B) ,@C.
1675 (if (and (eq (car-safe (car clauses
)) 'progn
)
1676 (eq (car (last (car clauses
))) t
))
1678 (setq clauses
(cons (nconc (butlast (car clauses
))
1679 (if (eq (car-safe (cadr clauses
))
1682 (list (cadr clauses
))))
1684 ;; A final (progn ,@A t) is moved outside of the `and'.
1685 (setq body
(cdr (butlast (pop clauses
)))))
1686 (push (pop clauses
) ands
)))
1687 (setq ands
(or (nreverse ands
) (list t
)))
1688 (list (if (cdr ands
) (cons 'and ands
) (car ands
))
1690 (let ((full (if body
1691 (append ands
(list (cons 'progn
(append body
'(t)))))
1693 (if (cdr full
) (cons 'and full
) (car full
))))))
1696 ;;; Other iteration control structures.
1699 (defmacro cl-do
(steps endtest
&rest body
)
1700 "The Common Lisp `do' loop.
1702 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1705 ((&rest
&or symbolp
(symbolp &optional form form
))
1707 cl-declarations body
)))
1708 (cl--expand-do-loop steps endtest body nil
))
1711 (defmacro cl-do
* (steps endtest
&rest body
)
1712 "The Common Lisp `do*' loop.
1714 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1715 (declare (indent 2) (debug cl-do
))
1716 (cl--expand-do-loop steps endtest body t
))
1718 (defun cl--expand-do-loop (steps endtest body star
)
1720 (,(if star
'let
* 'let
)
1721 ,(mapcar (lambda (c) (if (consp c
) (list (car c
) (nth 1 c
)) c
))
1723 (while (not ,(car endtest
))
1725 ,@(let ((sets (mapcar (lambda (c)
1726 (and (consp c
) (cdr (cdr c
))
1727 (list (car c
) (nth 2 c
))))
1729 (setq sets
(delq nil sets
))
1731 (list (cons (if (or star
(not (cdr sets
)))
1733 (apply 'append sets
))))))
1734 ,@(or (cdr endtest
) '(nil)))))
1737 (defmacro cl-dolist
(spec &rest body
)
1739 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1740 Then evaluate RESULT to get return value, default nil.
1741 An implicit nil block is established around the loop.
1743 \(fn (VAR LIST [RESULT]) BODY...)"
1744 (declare (debug ((symbolp form
&optional form
) cl-declarations body
))
1746 (let ((loop `(dolist ,spec
,@body
)))
1747 (if (advice-member-p 'cl--wrap-in-nil-block
'dolist
)
1748 loop
`(cl-block nil
,loop
))))
1751 (defmacro cl-dotimes
(spec &rest body
)
1752 "Loop a certain number of times.
1753 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1754 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1757 \(fn (VAR COUNT [RESULT]) BODY...)"
1758 (declare (debug cl-dolist
) (indent 1))
1759 (let ((loop `(dotimes ,spec
,@body
)))
1760 (if (advice-member-p 'cl--wrap-in-nil-block
'dotimes
)
1761 loop
`(cl-block nil
,loop
))))
1763 (defvar cl--tagbody-alist nil
)
1766 (defmacro cl-tagbody
(&rest labels-or-stmts
)
1767 "Execute statements while providing for control transfers to labels.
1768 Each element of LABELS-OR-STMTS can be either a label (integer or symbol)
1769 or a `cons' cell, in which case it's taken to be a statement.
1770 This distinction is made before performing macroexpansion.
1771 Statements are executed in sequence left to right, discarding any return value,
1772 stopping only when reaching the end of LABELS-OR-STMTS.
1773 Any statement can transfer control at any time to the statements that follow
1774 one of the labels with the special form (go LABEL).
1775 Labels have lexical scope and dynamic extent."
1777 (first-label (if (consp (car labels-or-stmts
))
1778 'cl--preamble
(pop labels-or-stmts
))))
1779 (let ((block (list first-label
)))
1780 (dolist (label-or-stmt labels-or-stmts
)
1781 (if (consp label-or-stmt
) (push label-or-stmt block
)
1782 ;; Add a "go to next block" to implement the fallthrough.
1783 (unless (eq 'go
(car-safe (car-safe block
)))
1784 (push `(go ,label-or-stmt
) block
))
1785 (push (nreverse block
) blocks
)
1786 (setq block
(list label-or-stmt
))))
1787 (unless (eq 'go
(car-safe (car-safe block
)))
1788 (push `(go cl--exit
) block
))
1789 (push (nreverse block
) blocks
))
1790 (let ((catch-tag (make-symbol "cl--tagbody-tag")))
1791 (push (cons 'cl--exit catch-tag
) cl--tagbody-alist
)
1792 (dolist (block blocks
)
1793 (push (cons (car block
) catch-tag
) cl--tagbody-alist
))
1795 `(let ((next-label ',first-label
))
1797 (not (eq (setq next-label
1802 `((go .
,(lambda (label)
1803 (let ((catch-tag (cdr (assq label cl--tagbody-alist
))))
1805 (error "Unknown cl-tagbody go label `%S'" label
))
1806 `(throw ',catch-tag
',label
))))
1807 ,@macroexpand-all-environment
)))))
1810 (defmacro cl-do-symbols
(spec &rest body
)
1811 "Loop over all symbols.
1812 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1815 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1817 (debug ((symbolp &optional form form
) cl-declarations body
)))
1818 ;; Apparently this doesn't have an implicit block.
1821 (mapatoms #'(lambda (,(car spec
)) ,@body
)
1822 ,@(and (cadr spec
) (list (cadr spec
))))
1826 (defmacro cl-do-all-symbols
(spec &rest body
)
1827 "Like `cl-do-symbols', but use the default obarray.
1829 \(fn (VAR [RESULT]) BODY...)"
1830 (declare (indent 1) (debug ((symbolp &optional form
) cl-declarations body
)))
1831 `(cl-do-symbols (,(car spec
) nil
,(cadr spec
)) ,@body
))
1837 (defmacro cl-psetq
(&rest args
)
1838 "Set SYMs to the values VALs in parallel.
1839 This is like `setq', except that all VAL forms are evaluated (in order)
1840 before assigning any symbols SYM to the corresponding values.
1842 \(fn SYM VAL SYM VAL ...)"
1843 (declare (debug setq
))
1844 (cons 'cl-psetf args
))
1847 ;;; Binding control structures.
1850 (defmacro cl-progv
(symbols values
&rest body
)
1851 "Bind SYMBOLS to VALUES dynamically in BODY.
1852 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1853 Each symbol in the first list is bound to the corresponding value in the
1854 second list (or to nil if VALUES is shorter than SYMBOLS); then the
1855 BODY forms are executed and their result is returned. This is much like
1856 a `let' form, except that the list of symbols can be computed at run-time."
1857 (declare (indent 2) (debug (form form body
)))
1858 (let ((bodyfun (make-symbol "body"))
1859 (binds (make-symbol "binds"))
1860 (syms (make-symbol "syms"))
1861 (vals (make-symbol "vals")))
1863 (let* ((,syms
,symbols
)
1865 (,bodyfun
(lambda () ,@body
))
1868 (push (list (pop ,syms
) (list 'quote
(pop ,vals
))) ,binds
))
1869 (eval (list 'let
,binds
(list 'funcall
(list 'quote
,bodyfun
))))))))
1871 (defconst cl--labels-magic
(make-symbol "cl--labels-magic"))
1873 (defvar cl--labels-convert-cache nil
)
1875 (defun cl--labels-convert (f)
1876 "Special macro-expander to rename (function F) references in `cl-labels'."
1878 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1879 ;; *after* handling `function', but we want to stop macroexpansion from
1880 ;; being applied infinitely, so we use a cache to return the exact `form'
1881 ;; being expanded even though we don't receive it.
1882 ((eq f
(car cl--labels-convert-cache
)) (cdr cl--labels-convert-cache
))
1884 (let* ((found (assq f macroexpand-all-environment
))
1885 (replacement (and found
1887 (funcall (cdr found
) cl--labels-magic
)))))
1888 (if (and replacement
(eq cl--labels-magic
(car replacement
)))
1890 (let ((res `(function ,f
)))
1891 (setq cl--labels-convert-cache
(cons f res
))
1895 (defmacro cl-flet
(bindings &rest body
)
1896 "Make local function definitions.
1897 Like `cl-labels' but the definitions are not recursive.
1898 Each binding can take the form (FUNC EXP) where
1899 FUNC is the function name, and EXP is an expression that returns the
1900 function value to which it should be bound, or it can take the more common
1901 form \(FUNC ARGLIST BODY...) which is a shorthand
1902 for (FUNC (lambda ARGLIST BODY)).
1904 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1905 (declare (indent 1) (debug ((&rest
(cl-defun)) cl-declarations body
)))
1906 (let ((binds ()) (newenv macroexpand-all-environment
))
1907 (dolist (binding bindings
)
1908 (let ((var (make-symbol (format "--cl-%s--" (car binding
))))
1909 (args-and-body (cdr binding
)))
1910 (if (and (= (length args-and-body
) 1) (symbolp (car args-and-body
)))
1911 ;; Optimize (cl-flet ((fun var)) body).
1912 (setq var
(car args-and-body
))
1913 (push (list var
(if (= (length args-and-body
) 1)
1915 `(cl-function (lambda .
,args-and-body
))))
1917 (push (cons (car binding
)
1918 (lambda (&rest args
)
1919 (if (eq (car args
) cl--labels-magic
)
1920 (list cl--labels-magic var
)
1921 `(funcall ,var
,@args
))))
1923 ;; FIXME: Eliminate those functions which aren't referenced.
1924 (macroexp-let* (nreverse binds
)
1927 ;; Don't override lexical-let's macro-expander.
1928 (if (assq 'function newenv
) newenv
1929 (cons (cons 'function
#'cl--labels-convert
) newenv
))))))
1932 (defmacro cl-flet
* (bindings &rest body
)
1933 "Make local function definitions.
1934 Like `cl-flet' but the definitions can refer to previous ones.
1936 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1937 (declare (indent 1) (debug cl-flet
))
1939 ((null bindings
) (macroexp-progn body
))
1940 ((null (cdr bindings
)) `(cl-flet ,bindings
,@body
))
1941 (t `(cl-flet (,(pop bindings
)) (cl-flet* ,bindings
,@body
)))))
1944 (defmacro cl-labels
(bindings &rest body
)
1945 "Make temporary function bindings.
1946 The bindings can be recursive and the scoping is lexical, but capturing them
1947 in closures will only work if `lexical-binding' is in use.
1949 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1950 (declare (indent 1) (debug cl-flet
))
1951 (let ((binds ()) (newenv macroexpand-all-environment
))
1952 (dolist (binding bindings
)
1953 (let ((var (make-symbol (format "--cl-%s--" (car binding
)))))
1954 (push (list var
`(cl-function (lambda .
,(cdr binding
)))) binds
)
1955 (push (cons (car binding
)
1956 (lambda (&rest args
)
1957 (if (eq (car args
) cl--labels-magic
)
1958 (list cl--labels-magic var
)
1959 (cl-list* 'funcall var args
))))
1961 (macroexpand-all `(letrec ,(nreverse binds
) ,@body
)
1962 ;; Don't override lexical-let's macro-expander.
1963 (if (assq 'function newenv
) newenv
1964 (cons (cons 'function
#'cl--labels-convert
) newenv
)))))
1966 ;; The following ought to have a better definition for use with newer
1969 (defmacro cl-macrolet
(bindings &rest body
)
1970 "Make temporary macro definitions.
1971 This is like `cl-flet', but for macros instead of functions.
1973 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
1976 ((&rest
(&define name
(&rest arg
) cl-declarations-or-string
1978 cl-declarations body
)))
1980 `(cl-macrolet (,(car bindings
)) (cl-macrolet ,(cdr bindings
) ,@body
))
1981 (if (null bindings
) (macroexp-progn body
)
1982 (let* ((name (caar bindings
))
1983 (res (cl--transform-lambda (cdar bindings
) name
)))
1985 (macroexpand-all (macroexp-progn body
)
1987 (eval `(cl-function (lambda ,@(cdr res
))) t
))
1988 macroexpand-all-environment
))))))
1990 (defconst cl--old-macroexpand
1991 (if (and (boundp 'cl--old-macroexpand
)
1992 (eq (symbol-function 'macroexpand
)
1993 #'cl--sm-macroexpand
))
1995 (symbol-function 'macroexpand
)))
1997 (defun cl--sm-macroexpand (exp &optional env
)
1998 "Special macro expander used inside `cl-symbol-macrolet'.
1999 This function replaces `macroexpand' during macro expansion
2000 of `cl-symbol-macrolet', and does the same thing as `macroexpand'
2001 except that it additionally expands symbol macros."
2002 (let ((macroexpand-all-environment env
))
2005 (setq exp
(funcall cl--old-macroexpand exp env
))
2008 ;; Perform symbol-macro expansion.
2009 (when (cdr (assq (symbol-name exp
) env
))
2010 (setq exp
(cadr (assq (symbol-name exp
) env
)))))
2012 ;; Convert setq to setf if required by symbol-macro expansion.
2013 (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env
))
2016 (while (and p
(symbolp (car p
))) (setq p
(cddr p
)))
2017 (if p
(setq exp
(cons 'setf args
))
2018 (setq exp
(cons 'setq args
))
2019 ;; Don't loop further.
2021 (`(,(or `let
`let
*) .
,(or `(,bindings .
,body
) dontcare
))
2022 ;; CL's symbol-macrolet treats re-bindings as candidates for
2023 ;; expansion (turning the let into a letf if needed), contrary to
2024 ;; Common-Lisp where such re-bindings hide the symbol-macro.
2025 (let ((letf nil
) (found nil
) (nbs ()))
2026 (dolist (binding bindings
)
2027 (let* ((var (if (symbolp binding
) binding
(car binding
)))
2028 (sm (assq (symbol-name var
) env
)))
2029 (push (if (not (cdr sm
))
2031 (let ((nexp (cadr sm
)))
2033 (unless (symbolp nexp
) (setq letf t
))
2034 (cons nexp
(cdr-safe binding
))))
2037 (setq exp
`(,(if letf
2038 (if (eq (car exp
) 'let
) 'cl-letf
'cl-letf
*)
2042 ;; FIXME: The behavior of CL made sense in a dynamically scoped
2043 ;; language, but for lexical scoping, Common-Lisp's behavior might
2044 ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
2045 ;; lexical-let), so maybe we should adjust the behavior based on
2046 ;; the use of lexical-binding.
2047 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
2048 ;; (let ((nbs ()) (found nil))
2049 ;; (dolist (binding bindings)
2050 ;; (let* ((var (if (symbolp binding) binding (car binding)))
2051 ;; (name (symbol-name var))
2052 ;; (val (and found (consp binding) (eq 'let* (car exp))
2053 ;; (list (macroexpand-all (cadr binding)
2055 ;; (push (if (assq name env)
2056 ;; ;; This binding should hide its symbol-macro,
2057 ;; ;; but given the way macroexpand-all works, we
2058 ;; ;; can't prevent application of `env' to the
2059 ;; ;; sub-expressions, so we need to α-rename this
2060 ;; ;; variable instead.
2061 ;; (let ((nvar (make-symbol
2062 ;; (copy-sequence name))))
2064 ;; (push (list name nvar) env)
2065 ;; (cons nvar (or val (cdr-safe binding))))
2066 ;; (if val (cons var val) binding))
2069 ;; (setq exp `(,(car exp)
2071 ;; ,@(macroexp-unprogn
2072 ;; (macroexpand-all (macroexp-progn body)
2079 (defmacro cl-symbol-macrolet
(bindings &rest body
)
2080 "Make symbol macro definitions.
2081 Within the body FORMs, references to the variable NAME will be replaced
2082 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
2084 \(fn ((NAME EXPANSION) ...) FORM...)"
2085 (declare (indent 1) (debug ((&rest
(symbol sexp
)) cl-declarations body
)))
2088 `(cl-symbol-macrolet (,(car bindings
))
2089 (cl-symbol-macrolet ,(cdr bindings
) ,@body
)))
2090 ((null bindings
) (macroexp-progn body
))
2092 (let ((previous-macroexpand (symbol-function 'macroexpand
)))
2095 (fset 'macroexpand
#'cl--sm-macroexpand
)
2097 ;; FIXME: For N bindings, this will traverse `body' N times!
2098 (macroexpand-all (macroexp-progn body
)
2099 (cons (list (symbol-name (caar bindings
))
2100 (cl-cadar bindings
))
2101 macroexpand-all-environment
))))
2102 (if (or (null (cdar bindings
)) (cl-cddar bindings
))
2103 (macroexp--warn-and-return
2104 (format "Malformed `cl-symbol-macrolet' binding: %S"
2108 (fset 'macroexpand previous-macroexpand
))))))
2110 ;;; Multiple values.
2113 (defmacro cl-multiple-value-bind
(vars form
&rest body
)
2114 "Collect multiple return values.
2115 FORM must return a list; the BODY is then executed with the first N elements
2116 of this list bound (`let'-style) to each of the symbols SYM in turn. This
2117 is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
2118 simulate true multiple return values. For compatibility, (cl-values A B C) is
2119 a synonym for (list A B C).
2121 \(fn (SYM...) FORM BODY)"
2122 (declare (indent 2) (debug ((&rest symbolp
) form body
)))
2123 (let ((temp (make-symbol "--cl-var--")) (n -
1))
2124 `(let* ((,temp
,form
)
2125 ,@(mapcar (lambda (v)
2126 (list v
`(nth ,(setq n
(1+ n
)) ,temp
)))
2131 (defmacro cl-multiple-value-setq
(vars form
)
2132 "Collect multiple return values.
2133 FORM must return a list; the first N elements of this list are stored in
2134 each of the symbols SYM in turn. This is analogous to the Common Lisp
2135 `multiple-value-setq' macro, using lists to simulate true multiple return
2136 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
2138 \(fn (SYM...) FORM)"
2139 (declare (indent 1) (debug ((&rest symbolp
) form
)))
2140 (cond ((null vars
) `(progn ,form nil
))
2141 ((null (cdr vars
)) `(setq ,(car vars
) (car ,form
)))
2143 (let* ((temp (make-symbol "--cl-var--")) (n 0))
2144 `(let ((,temp
,form
))
2145 (prog1 (setq ,(pop vars
) (car ,temp
))
2146 (setq ,@(apply #'nconc
2148 (list v
`(nth ,(setq n
(1+ n
))
2156 (defmacro cl-locally
(&rest body
)
2157 "Equivalent to `progn'."
2161 (defmacro cl-the
(type form
)
2162 "Return FORM. If type-checking is enabled, assert that it is of TYPE."
2163 (declare (indent 1) (debug (cl-type-spec form
)))
2164 (if (not (or (not (cl--compiling-file))
2165 (< cl--optimize-speed
3)
2166 (= cl--optimize-safety
3)))
2168 (macroexp-let2 macroexp-copyable-p temp form
2169 `(progn (unless (cl-typep ,temp
',type
)
2170 (signal 'wrong-type-argument
2171 (list ',type
,temp
',form
)))
2174 (defvar cl--proclaim-history t
) ; for future compilers
2175 (defvar cl--declare-stack t
) ; for future compilers
2177 (defun cl--do-proclaim (spec hist
)
2178 (and hist
(listp cl--proclaim-history
) (push spec cl--proclaim-history
))
2179 (cond ((eq (car-safe spec
) 'special
)
2180 (if (boundp 'byte-compile-bound-variables
)
2181 (setq byte-compile-bound-variables
2182 (append (cdr spec
) byte-compile-bound-variables
))))
2184 ((eq (car-safe spec
) 'inline
)
2185 (while (setq spec
(cdr spec
))
2186 (or (memq (get (car spec
) 'byte-optimizer
)
2187 '(nil byte-compile-inline-expand
))
2188 (error "%s already has a byte-optimizer, can't make it inline"
2190 (put (car spec
) 'byte-optimizer
'byte-compile-inline-expand
)))
2192 ((eq (car-safe spec
) 'notinline
)
2193 (while (setq spec
(cdr spec
))
2194 (if (eq (get (car spec
) 'byte-optimizer
)
2195 'byte-compile-inline-expand
)
2196 (put (car spec
) 'byte-optimizer nil
))))
2198 ((eq (car-safe spec
) 'optimize
)
2199 (let ((speed (assq (nth 1 (assq 'speed
(cdr spec
)))
2200 '((0 nil
) (1 t
) (2 t
) (3 t
))))
2201 (safety (assq (nth 1 (assq 'safety
(cdr spec
)))
2202 '((0 t
) (1 t
) (2 t
) (3 nil
)))))
2203 (if speed
(setq cl--optimize-speed
(car speed
)
2204 byte-optimize
(nth 1 speed
)))
2205 (if safety
(setq cl--optimize-safety
(car safety
)
2206 byte-compile-delete-errors
(nth 1 safety
)))))
2208 ((and (eq (car-safe spec
) 'warn
) (boundp 'byte-compile-warnings
))
2209 (while (setq spec
(cdr spec
))
2210 (if (consp (car spec
))
2211 (if (eq (cl-cadar spec
) 0)
2212 (byte-compile-disable-warning (caar spec
))
2213 (byte-compile-enable-warning (caar spec
)))))))
2216 ;;; Process any proclamations made before cl-macs was loaded.
2217 (defvar cl--proclaims-deferred
)
2218 (let ((p (reverse cl--proclaims-deferred
)))
2219 (while p
(cl--do-proclaim (pop p
) t
))
2220 (setq cl--proclaims-deferred nil
))
2223 (defmacro cl-declare
(&rest specs
)
2224 "Declare SPECS about the current function while compiling.
2227 (cl-declare (warn 0))
2229 will turn off byte-compile warnings in the function.
2230 See Info node `(cl)Declarations' for details."
2231 (if (cl--compiling-file)
2233 (if (listp cl--declare-stack
) (push (car specs
) cl--declare-stack
))
2234 (cl--do-proclaim (pop specs
) nil
)))
2237 ;;; The standard modify macros.
2239 ;; `setf' is now part of core Elisp, defined in gv.el.
2242 (defmacro cl-psetf
(&rest args
)
2243 "Set PLACEs to the values VALs in parallel.
2244 This is like `setf', except that all VAL forms are evaluated (in order)
2245 before assigning any PLACEs to the corresponding values.
2247 \(fn PLACE VAL PLACE VAL ...)"
2248 (declare (debug setf
))
2249 (let ((p args
) (simple t
) (vars nil
))
2251 (if (or (not (symbolp (car p
))) (cl--expr-depends-p (nth 1 p
) vars
))
2253 (if (memq (car p
) vars
)
2254 (error "Destination duplicated in psetf: %s" (car p
)))
2256 (or p
(error "Odd number of arguments to cl-psetf"))
2259 `(progn (setq ,@args
) nil
)
2260 (setq args
(reverse args
))
2261 (let ((expr `(setf ,(cadr args
) ,(car args
))))
2262 (while (setq args
(cddr args
))
2263 (setq expr
`(setf ,(cadr args
) (prog1 ,(car args
) ,expr
))))
2264 `(progn ,expr nil
)))))
2267 (defmacro cl-remf
(place tag
)
2268 "Remove TAG from property list PLACE.
2269 PLACE may be a symbol, or any generalized variable allowed by `setf'.
2270 The form returns true if TAG was found and removed, nil otherwise."
2271 (declare (debug (place form
)))
2272 (gv-letplace (tval setter
) place
2273 (macroexp-let2 macroexp-copyable-p ttag tag
2274 `(if (eq ,ttag
(car ,tval
))
2275 (progn ,(funcall setter
`(cddr ,tval
))
2277 (cl--do-remf ,tval
,ttag
)))))
2280 (defmacro cl-shiftf
(place &rest args
)
2281 "Shift left among PLACEs.
2282 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2283 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2286 (declare (debug (&rest place
)))
2289 ((symbolp place
) `(prog1 ,place
(setq ,place
(cl-shiftf ,@args
))))
2291 (gv-letplace (getter setter
) place
2293 ,(funcall setter
`(cl-shiftf ,@args
)))))))
2296 (defmacro cl-rotatef
(&rest args
)
2297 "Rotate left among PLACEs.
2298 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2299 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
2302 (declare (debug (&rest place
)))
2303 (if (not (memq nil
(mapcar 'symbolp args
)))
2308 (setq sets
(nconc sets
(list (pop args
) (car args
)))))
2309 `(cl-psetf ,@sets
,(car args
) ,first
)))
2310 (let* ((places (reverse args
))
2311 (temp (make-symbol "--cl-rotatef--"))
2315 (gv-letplace (getter setter
) (pop places
)
2316 `(prog1 ,getter
,(funcall setter form
)))))
2317 (gv-letplace (getter setter
) (car places
)
2318 (macroexp-let* `((,temp
,getter
))
2319 `(progn ,(funcall setter form
) nil
))))))
2321 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2322 ;; previous state. If the getter/setter loses information, that info is
2325 (defun cl--letf (bindings simplebinds binds body
)
2326 ;; It's not quite clear what the semantics of cl-letf should be.
2327 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2328 ;; that the actual assignments ("bindings") should only happen after
2329 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2330 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2331 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2333 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2335 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2336 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2338 (if (and (null binds
) (null simplebinds
)) (macroexp-progn body
)
2339 `(let* (,@(mapcar (lambda (x)
2340 (pcase-let ((`(,vold
,getter
,_setter
,_vnew
) x
))
2341 (list vold getter
)))
2350 ;; If there's no vnew, do nothing.
2351 (`(,_vold
,_getter
,setter
,vnew
)
2352 (funcall setter vnew
))))
2355 ,@(mapcar (lambda (x)
2356 (pcase-let ((`(,vold
,_getter
,setter
,_vnew
) x
))
2357 (funcall setter vold
)))
2359 (let ((binding (car bindings
)))
2360 (gv-letplace (getter setter
) (car binding
)
2361 (macroexp-let2 nil vnew
(cadr binding
)
2362 (if (symbolp (car binding
))
2363 ;; Special-case for simple variables.
2364 (cl--letf (cdr bindings
)
2365 (cons `(,getter
,(if (cdr binding
) vnew getter
))
2368 (cl--letf (cdr bindings
) simplebinds
2369 (cons `(,(make-symbol "old") ,getter
,setter
2370 ,@(if (cdr binding
) (list vnew
)))
2375 (defmacro cl-letf
(bindings &rest body
)
2376 "Temporarily bind to PLACEs.
2377 This is the analogue of `let', but with generalized variables (in the
2378 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2379 VALUE, then the BODY forms are executed. On exit, either normally or
2380 because of a `throw' or error, the PLACEs are set back to their original
2381 values. Note that this macro is *not* available in Common Lisp.
2382 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2383 the PLACE is not modified before executing BODY.
2385 \(fn ((PLACE VALUE) ...) BODY...)"
2386 (declare (indent 1) (debug ((&rest
(gate gv-place
&optional form
)) body
)))
2387 (if (and (not (cdr bindings
)) (cdar bindings
) (symbolp (caar bindings
)))
2388 `(let ,bindings
,@body
)
2389 (cl--letf bindings
() () body
)))
2392 (defmacro cl-letf
* (bindings &rest body
)
2393 "Temporarily bind to PLACEs.
2394 Like `cl-letf' but where the bindings are performed one at a time,
2395 rather than all at the end (i.e. like `let*' rather than like `let')."
2396 (declare (indent 1) (debug cl-letf
))
2397 (dolist (binding (reverse bindings
))
2398 (setq body
(list `(cl-letf (,binding
) ,@body
))))
2399 (macroexp-progn body
))
2402 (defmacro cl-callf
(func place
&rest args
)
2403 "Set PLACE to (FUNC PLACE ARGS...).
2404 FUNC should be an unquoted function name. PLACE may be a symbol,
2405 or any generalized variable allowed by `setf'."
2406 (declare (indent 2) (debug (cl-function place
&rest form
)))
2407 (gv-letplace (getter setter
) place
2408 (let* ((rargs (cons getter args
)))
2410 (if (symbolp func
) (cons func rargs
)
2411 `(funcall #',func
,@rargs
))))))
2414 (defmacro cl-callf2
(func arg1 place
&rest args
)
2415 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2416 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2418 \(fn FUNC ARG1 PLACE ARGS...)"
2419 (declare (indent 3) (debug (cl-function form place
&rest form
)))
2420 (if (and (cl--safe-expr-p arg1
) (cl--simple-expr-p place
) (symbolp func
))
2421 `(setf ,place
(,func
,arg1
,place
,@args
))
2422 (macroexp-let2 nil a1 arg1
2423 (gv-letplace (getter setter
) place
2424 (let* ((rargs (cl-list* a1 getter args
)))
2426 (if (symbolp func
) (cons func rargs
)
2427 `(funcall #',func
,@rargs
))))))))
2430 (defmacro cl-defsubst
(name args
&rest body
)
2431 "Define NAME as a function.
2432 Like `defun', except the function is automatically declared `inline' and
2433 the arguments are immutable.
2434 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2435 surrounded by (cl-block NAME ...).
2436 The function's arguments should be treated as immutable.
2438 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2439 (declare (debug cl-defun
) (indent 2))
2440 (let* ((argns (cl--arglist-args args
))
2441 (real-args (if (eq '&cl-defs
(car args
)) (cddr args
) args
))
2443 ;; (pbody (cons 'progn body))
2445 (while (and p
(eq (cl--expr-contains real-args
(car p
)) 1)) (pop p
))
2447 ,(if p nil
; give up if defaults refer to earlier args
2448 `(cl-define-compiler-macro ,name
2449 ,(if (memq '&key args
)
2450 `(&whole cl-whole
&cl-quote
,@args
)
2451 (cons '&cl-quote args
))
2452 (cl--defsubst-expand
2453 ',argns
'(cl-block ,name
,@body
)
2454 ;; We used to pass `simple' as
2455 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2456 ;; But this is much too simplistic since it
2457 ;; does not pay attention to the argvs (and
2458 ;; cl-expr-access-order itself is also too naive).
2460 ,(and (memq '&key args
) 'cl-whole
) nil
,@argns
)))
2461 (cl-defun ,name
,args
,@body
))))
2463 (defun cl--defsubst-expand (argns body simple whole _unsafe
&rest argvs
)
2464 (if (and whole
(not (cl--safe-expr-p (cons 'progn argvs
)))) whole
2465 (if (cl--simple-exprs-p argvs
) (setq simple t
))
2468 (cl-mapcar (lambda (argn argv
)
2469 (if (or simple
(macroexp-const-p argv
))
2470 (progn (push (cons argn argv
) substs
)
2474 ;; FIXME: `sublis/subst' will happily substitute the symbol
2475 ;; `argn' in places where it's not used as a reference
2477 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2478 ;; scope, leading to name capture.
2479 (setq body
(cond ((null substs
) body
)
2480 ((null (cdr substs
))
2481 (cl-subst (cdar substs
) (caar substs
) body
))
2482 (t (cl--sublis substs body
))))
2483 (if lets
`(let ,lets
,body
) body
))))
2485 (defun cl--sublis (alist tree
)
2486 "Perform substitutions indicated by ALIST in TREE (non-destructively)."
2487 (let ((x (assq tree alist
)))
2491 (cons (cl--sublis alist
(car tree
)) (cl--sublis alist
(cdr tree
))))
2496 (defmacro cl--find-class
(type)
2497 `(get ,type
'cl--class
))
2499 ;; Rather than hard code cl-structure-object, we indirect through this variable
2500 ;; for bootstrapping reasons.
2501 (defvar cl--struct-default-parent nil
)
2504 (defmacro cl-defstruct
(struct &rest descs
)
2505 "Define a struct type.
2506 This macro defines a new data type called NAME that stores data
2507 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2508 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2509 You can use the accessors to set the corresponding slots, via `setf'.
2511 NAME may instead take the form (NAME OPTIONS...), where each
2512 OPTION is either a single keyword or (KEYWORD VALUE) where
2513 KEYWORD can be one of :conc-name, :constructor, :copier, :predicate,
2514 :type, :named, :initial-offset, :print-function, or :include.
2516 Each SLOT may instead take the form (SNAME SDEFAULT SOPTIONS...), where
2517 SDEFAULT is the default value of that slot and SOPTIONS are keyword-value
2518 pairs for that slot.
2519 Currently, only one keyword is supported, `:read-only'. If this has a
2520 non-nil value, that slot cannot be set via `setf'.
2522 \(fn NAME SLOTS...)"
2523 (declare (doc-string 2) (indent 1)
2525 (&define
;Makes top-level form not be wrapped.
2529 (&or
[":conc-name" symbolp
]
2530 [":constructor" symbolp
&optional cl-lambda-list
]
2532 [":predicate" symbolp
]
2533 [":include" symbolp
&rest sexp
] ;; Not finished.
2534 ;; The following are not supported.
2535 ;; [":print-function" ...]
2537 ;; [":initial-offset" ...]
2540 ;; All the above is for the following def-form.
2541 &rest
&or symbolp
(symbolp def-form
2542 &optional
":read-only" sexp
))))
2543 (let* ((name (if (consp struct
) (car struct
) struct
))
2544 (opts (cdr-safe struct
))
2547 (conc-name (concat (symbol-name name
) "-"))
2548 (constructor (intern (format "make-%s" name
)))
2550 (copier (intern (format "copy-%s" name
)))
2551 (predicate (intern (format "%s-p" name
)))
2552 (print-func nil
) (print-auto nil
)
2553 (safety (if (cl--compiling-file) cl--optimize-safety
3))
2555 (tag (intern (format "cl-struct-%s" name
)))
2556 (tag-symbol (intern (format "cl-struct-%s-tags" name
)))
2562 (docstring (if (stringp (car descs
)) (pop descs
)))
2563 pred-form pred-check
)
2564 (setq descs
(cons '(cl-tag-slot)
2565 (mapcar (function (lambda (x) (if (consp x
) x
(list x
))))
2568 (let ((opt (if (consp (car opts
)) (caar opts
) (car opts
)))
2569 (args (cdr-safe (pop opts
))))
2570 (cond ((eq opt
:conc-name
)
2572 (setq conc-name
(if (car args
)
2573 (symbol-name (car args
)) ""))))
2574 ((eq opt
:constructor
)
2577 ;; If this defines a constructor of the same name as
2578 ;; the default one, don't define the default.
2579 (if (eq (car args
) constructor
)
2580 (setq constructor nil
))
2581 (push args constrs
))
2582 (if args
(setq constructor
(car args
)))))
2584 (if args
(setq copier
(car args
))))
2585 ((eq opt
:predicate
)
2586 (if args
(setq predicate
(car args
))))
2588 ;; FIXME: Actually, we can include more than once as long as
2589 ;; we include EIEIO classes rather than cl-structs!
2590 (when include-name
(error "Can't :include more than once"))
2591 (setq include-name
(car args
))
2592 (setq include-descs
(mapcar (function
2594 (if (consp x
) x
(list x
))))
2596 ((eq opt
:print-function
)
2597 (setq print-func
(car args
)))
2599 (setq type
(car args
)))
2602 ((eq opt
:initial-offset
)
2603 (setq descs
(nconc (make-list (car args
) '(cl-skip-slot))
2606 (error "Slot option %s unrecognized" opt
)))))
2607 (unless (or include-name type
)
2608 (setq include-name cl--struct-default-parent
))
2609 (when include-name
(setq include
(cl--struct-get-class include-name
)))
2612 `(progn (funcall #',print-func cl-x cl-s cl-n
) t
))
2613 (or type
(and include
(not (cl--struct-class-print include
)))
2615 print-func
(and (or (not (or include type
)) (null print-func
))
2617 (princ ,(format "#S(%s" name
) cl-s
))))))
2619 (let* ((inc-type (cl--struct-class-type include
))
2620 (old-descs (cl-struct-slot-info include
)))
2621 (and type
(not (eq inc-type type
))
2622 (error ":type disagrees with :include for %s" name
))
2623 (while include-descs
2624 (setcar (memq (or (assq (caar include-descs
) old-descs
)
2625 (error "No slot %s in included struct %s"
2626 (caar include-descs
) include
))
2628 (pop include-descs
)))
2629 (setq descs
(append old-descs
(delq (assq 'cl-tag-slot descs
) descs
))
2631 named
(if type
(assq 'cl-tag-slot descs
) 'true
))
2632 (if (cl--struct-class-named include
) (setq tag name named t
)))
2635 (or (memq type
'(vector list
))
2636 (error "Invalid :type specifier: %s" type
))
2637 (if named
(setq tag name
)))
2638 (setq named
'true
)))
2639 (or named
(setq descs
(delq (assq 'cl-tag-slot descs
) descs
)))
2640 (when (and (null predicate
) named
)
2641 (setq predicate
(intern (format "cl--struct-%s-p" name
))))
2642 (setq pred-form
(and named
2643 (let ((pos (- (length descs
)
2644 (length (memq (assq 'cl-tag-slot descs
)
2647 ((memq type
'(nil vector
))
2648 `(and (vectorp cl-x
)
2649 (>= (length cl-x
) ,(length descs
))
2650 (memq (aref cl-x
,pos
) ,tag-symbol
)))
2651 ((= pos
0) `(memq (car-safe cl-x
) ,tag-symbol
))
2652 (t `(and (consp cl-x
)
2653 (memq (nth ,pos cl-x
) ,tag-symbol
))))))
2654 pred-check
(and pred-form
(> safety
0)
2655 (if (and (eq (cl-caadr pred-form
) 'vectorp
)
2657 (cons 'and
(cl-cdddr pred-form
))
2658 `(,predicate cl-x
))))
2659 (let ((pos 0) (descp descs
))
2661 (let* ((desc (pop descp
))
2663 (if (memq slot
'(cl-tag-slot cl-skip-slot
))
2666 (push (and (eq slot
'cl-tag-slot
) `',tag
)
2668 (if (assq slot descp
)
2669 (error "Duplicate slots named %s in %s" slot name
))
2670 (let ((accessor (intern (format "%s%s" conc-name slot
))))
2672 (push (nth 1 desc
) defaults
)
2673 (push `(cl-defsubst ,accessor
(cl-x)
2674 (declare (side-effect-free t
))
2676 (list `(or ,pred-check
2677 (signal 'wrong-type-argument
2678 (list ',name cl-x
)))))
2679 ,(if (memq type
'(nil vector
)) `(aref cl-x
,pos
)
2680 (if (= pos
0) '(car cl-x
)
2683 (if (cadr (memq :read-only
(cddr desc
)))
2684 (push `(gv-define-expander ,accessor
2685 (lambda (_cl-do _cl-x
)
2686 (error "%s is a read-only slot" ',accessor
)))
2688 ;; For normal slots, we don't need to define a setf-expander,
2689 ;; since gv-get can use the compiler macro to get the
2691 ;; (push `(gv-define-setter ,accessor (cl-val cl-x)
2692 ;; ;; If cl is loaded only for compilation,
2693 ;; ;; the call to cl--struct-setf-expander would
2694 ;; ;; cause a warning because it may not be
2695 ;; ;; defined at run time. Suppress that warning.
2697 ;; (declare-function
2698 ;; cl--struct-setf-expander "cl-macs"
2699 ;; (x name accessor pred-form pos))
2700 ;; (cl--struct-setf-expander
2701 ;; cl-val cl-x ',name ',accessor
2702 ;; ,(and pred-check `',pred-check)
2708 (list `(princ ,(format " %s" slot
) cl-s
)
2709 `(prin1 (,accessor cl-x
) cl-s
)))))))
2710 (setq pos
(1+ pos
))))
2711 (setq slots
(nreverse slots
)
2712 defaults
(nreverse defaults
))
2714 (push `(cl-defsubst ,predicate
(cl-x)
2715 (declare (side-effect-free error-free
))
2716 ,(if (eq (car pred-form
) 'and
)
2717 (append pred-form
'(t))
2718 `(and ,pred-form t
)))
2720 (push `(put ',name
'cl-deftype-satisfies
',predicate
) forms
))
2722 (push `(defalias ',copier
#'copy-sequence
) forms
))
2724 (push (list constructor
2725 (cons '&key
(delq nil
(copy-sequence slots
))))
2728 (let* ((name (caar constrs
))
2729 (rest (cdr (pop constrs
)))
2732 (anames (cl--arglist-args args
))
2733 (make (cl-mapcar (function (lambda (s d
) (if (memq s anames
) s d
)))
2735 (push `(cl-defsubst ,name
2736 (&cl-defs
(nil ,@descs
) ,@args
)
2737 ,@(if (stringp doc
) (list doc
)
2738 (if (stringp docstring
) (list docstring
)))
2739 ,@(if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs
)))
2740 '((declare (side-effect-free t
))))
2741 (,(or type
#'vector
) ,@make
))
2743 (if print-auto
(nconc print-func
(list '(princ ")" cl-s
) t
)))
2744 ;; Don't bother adding to cl-custom-print-functions since it's not used
2745 ;; by anything anyway!
2747 ;; (push `(if (boundp 'cl-custom-print-functions)
2749 ;; ;; The auto-generated function does not pay attention to
2750 ;; ;; the depth argument cl-n.
2751 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2752 ;; (and ,pred-form ,print-func))
2753 ;; cl-custom-print-functions))
2756 (defvar ,tag-symbol
)
2758 ;; Call cl-struct-define during compilation as well, so that
2759 ;; a subsequent cl-defstruct in the same file can correctly include this
2760 ;; struct as a parent.
2762 (cl-struct-define ',name
,docstring
',include-name
2763 ',type
,(eq named t
) ',descs
',tag-symbol
',tag
2767 ;;; Add cl-struct support to pcase
2769 (defun cl--struct-all-parents (class)
2770 (when (cl--struct-class-p class
)
2772 (classes (list class
)))
2774 (while (let ((class (pop classes
)))
2778 (cl--class-parents class
)))))
2782 (pcase-defmacro cl-struct
(type &rest fields
)
2783 "Pcase patterns to match cl-structs.
2784 Elements of FIELDS can be of the form (NAME UPAT) in which case the contents of
2785 field NAME is matched against UPAT, or they can be of the form NAME which
2786 is a shorthand for (NAME NAME)."
2787 (declare (debug (sexp &rest
[&or
(sexp pcase-UPAT
) sexp
])))
2788 `(and (pred (pcase--flip cl-typep
',type
))
2791 (let* ((name (if (consp field
) (car field
) field
))
2792 (pat (if (consp field
) (cadr field
) field
)))
2793 `(app ,(if (eq (cl-struct-sequence-type type
) 'list
)
2794 `(nth ,(cl-struct-slot-offset type name
))
2795 `(pcase--flip aref
,(cl-struct-slot-offset type name
)))
2799 (defun cl--pcase-mutually-exclusive-p (orig pred1 pred2
)
2800 "Extra special cases for `cl-typep' predicates."
2801 (let* ((x1 pred1
) (x2 pred2
)
2803 (and (eq 'pcase--flip
(car-safe x1
)) (setq x1
(cdr x1
))
2804 (eq 'cl-typep
(car-safe x1
)) (setq x1
(cdr x1
))
2805 (null (cdr-safe x1
)) (setq x1
(car x1
))
2806 (eq 'quote
(car-safe x1
)) (cadr x1
)))
2808 (and (eq 'pcase--flip
(car-safe x2
)) (setq x2
(cdr x2
))
2809 (eq 'cl-typep
(car-safe x2
)) (setq x2
(cdr x2
))
2810 (null (cdr-safe x2
)) (setq x2
(car x2
))
2811 (eq 'quote
(car-safe x2
)) (cadr x2
))))
2813 (and (symbolp t1
) (symbolp t2
)
2814 (let ((c1 (cl--find-class t1
))
2815 (c2 (cl--find-class t2
)))
2817 (not (or (memq c1
(cl--struct-all-parents c2
))
2818 (memq c2
(cl--struct-all-parents c1
)))))))
2819 (let ((c1 (and (symbolp t1
) (cl--find-class t1
))))
2820 (and c1
(cl--struct-class-p c1
)
2821 (funcall orig
(if (eq 'list
(cl-struct-sequence-type t1
))
2824 (let ((c2 (and (symbolp t2
) (cl--find-class t2
))))
2825 (and c2
(cl--struct-class-p c2
)
2827 (if (eq 'list
(cl-struct-sequence-type t2
))
2829 (funcall orig pred1 pred2
))))
2830 (advice-add 'pcase--mutually-exclusive-p
2831 :around
#'cl--pcase-mutually-exclusive-p
)
2834 (defun cl-struct-sequence-type (struct-type)
2835 "Return the sequence used to build STRUCT-TYPE.
2836 STRUCT-TYPE is a symbol naming a struct type. Return 'vector or
2837 'list, or nil if STRUCT-TYPE is not a struct type. "
2838 (declare (side-effect-free t
) (pure t
))
2839 (cl--struct-class-type (cl--struct-get-class struct-type
)))
2841 (defun cl-struct-slot-info (struct-type)
2842 "Return a list of slot names of struct STRUCT-TYPE.
2843 Each entry is a list (SLOT-NAME . OPTS), where SLOT-NAME is a
2844 slot name symbol and OPTS is a list of slot options given to
2845 `cl-defstruct'. Dummy slots that represent the struct name and
2846 slots skipped by :initial-offset may appear in the list."
2847 (declare (side-effect-free t
) (pure t
))
2848 (let* ((class (cl--struct-get-class struct-type
))
2849 (slots (cl--struct-class-slots class
))
2850 (type (cl--struct-class-type class
))
2851 (descs (if type
() (list '(cl-tag-slot)))))
2852 (dotimes (i (length slots
))
2853 (let ((slot (aref slots i
)))
2854 (push `(,(cl--slot-descriptor-name slot
)
2855 ,(cl--slot-descriptor-initform slot
)
2856 ,@(if (not (eq (cl--slot-descriptor-type slot
) t
))
2857 `(:type
,(cl--slot-descriptor-type slot
)))
2858 ,@(cl--slot-descriptor-props slot
))
2862 (defun cl-struct-slot-offset (struct-type slot-name
)
2863 "Return the offset of slot SLOT-NAME in STRUCT-TYPE.
2864 The returned zero-based slot index is relative to the start of
2865 the structure data type and is adjusted for any structure name
2866 and :initial-offset slots. Signal error if struct STRUCT-TYPE
2867 does not contain SLOT-NAME."
2868 (declare (side-effect-free t
) (pure t
))
2869 (or (gethash slot-name
2870 (cl--class-index-table (cl--struct-get-class struct-type
)))
2871 (error "struct %s has no slot %s" struct-type slot-name
)))
2873 (defvar byte-compile-function-environment
)
2874 (defvar byte-compile-macro-environment
)
2876 (defun cl--macroexp-fboundp (sym)
2877 "Return non-nil if SYM will be bound when we run the code.
2878 Of course, we really can't know that for sure, so it's just a heuristic."
2880 (and (cl--compiling-file)
2881 (or (cdr (assq sym byte-compile-function-environment
))
2882 (cdr (assq sym byte-compile-macro-environment
))))))
2884 (put 'null
'cl-deftype-satisfies
#'null
)
2885 (put 'atom
'cl-deftype-satisfies
#'atom
)
2886 (put 'real
'cl-deftype-satisfies
#'numberp
)
2887 (put 'fixnum
'cl-deftype-satisfies
#'integerp
)
2888 (put 'base-char
'cl-deftype-satisfies
#'characterp
)
2889 (put 'character
'cl-deftype-satisfies
#'integerp
)
2893 (define-inline cl-typep
(val type
)
2894 (inline-letevals (val)
2895 (pcase (inline-const-val type
)
2896 ((and `(,name .
,args
) (guard (get name
'cl-deftype-handler
)))
2898 (cl-typep ,val
',(apply (get name
'cl-deftype-handler
) args
))))
2899 (`(,(and name
(or 'integer
'float
'real
'number
))
2900 .
,(or `(,min
,max
) pcase--dontcare
))
2902 (and (cl-typep ,val
',name
)
2903 ,(if (memq min
'(* nil
)) t
2905 (inline-quote (> ,val
',(car min
)))
2906 (inline-quote (>= ,val
',min
))))
2907 ,(if (memq max
'(* nil
)) t
2909 (inline-quote (< ,val
',(car max
)))
2910 (inline-quote (<= ,val
',max
)))))))
2911 (`(not ,type
) (inline-quote (not (cl-typep ,val
',type
))))
2912 (`(,(and name
(or 'and
'or
)) .
,types
)
2914 ((null types
) (inline-quote ',(eq name
'and
)))
2916 (inline-quote (cl-typep ,val
',(car types
))))
2918 (let ((head (car types
))
2919 (rest `(,name .
,(cdr types
))))
2922 (inline-quote (and (cl-typep ,val
',head
)
2923 (cl-typep ,val
',rest
))))
2925 (inline-quote (or (cl-typep ,val
',head
)
2926 (cl-typep ,val
',rest
)))))))))
2927 (`(eql ,v
) (inline-quote (and (eql ,val
',v
) t
)))
2928 (`(member .
,args
) (inline-quote (and (memql ,val
',args
) t
)))
2929 (`(satisfies ,pred
) (inline-quote (funcall #',pred
,val
)))
2930 ((and (pred symbolp
) type
(guard (get type
'cl-deftype-handler
)))
2932 (cl-typep ,val
',(funcall (get type
'cl-deftype-handler
)))))
2933 ((and (pred symbolp
) type
(guard (get type
'cl-deftype-satisfies
)))
2934 (inline-quote (funcall #',(get type
'cl-deftype-satisfies
) ,val
)))
2935 ((and (or 'nil
't
) type
) (inline-quote ',type
))
2936 ((and (pred symbolp
) type
)
2937 (let* ((name (symbol-name type
))
2938 (namep (intern (concat name
"p"))))
2940 ((cl--macroexp-fboundp namep
) (inline-quote (funcall #',namep
,val
)))
2941 ((cl--macroexp-fboundp
2942 (setq namep
(intern (concat name
"-p"))))
2943 (inline-quote (funcall #',namep
,val
)))
2944 ((cl--macroexp-fboundp type
) (inline-quote (funcall #',type
,val
)))
2945 (t (error "Unknown type %S" type
)))))
2946 (type (error "Bad type spec: %s" type
)))))
2950 (defmacro cl-check-type
(form type
&optional string
)
2951 "Verify that FORM is of type TYPE; signal an error if not.
2952 STRING is an optional description of the desired type."
2953 (declare (debug (place cl-type-spec
&optional stringp
)))
2954 (and (or (not (cl--compiling-file))
2955 (< cl--optimize-speed
3) (= cl--optimize-safety
3))
2956 (macroexp-let2 macroexp-copyable-p temp form
2957 `(progn (or (cl-typep ,temp
',type
)
2958 (signal 'wrong-type-argument
2959 (list ,(or string
`',type
) ,temp
',form
)))
2963 (defmacro cl-assert
(form &optional show-args string
&rest args
)
2964 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
2965 "Verify that FORM returns non-nil; signal an error if not.
2966 Second arg SHOW-ARGS means to include arguments of FORM in message.
2967 Other args STRING and ARGS... are arguments to be passed to `error'.
2968 They are not evaluated unless the assertion fails. If STRING is
2969 omitted, a default message listing FORM itself is used."
2970 (declare (debug (form &rest form
)))
2971 (and (or (not (cl--compiling-file))
2972 (< cl--optimize-speed
3) (= cl--optimize-safety
3))
2973 (let ((sargs (and show-args
2974 (delq nil
(mapcar (lambda (x)
2975 (unless (macroexp-const-p x
)
2980 (cl--assertion-failed
2981 ',form
,@(if (or string sargs args
)
2982 `(,string
(list ,@sargs
) (list ,@args
)))))
2985 ;;; Compiler macros.
2988 (defmacro cl-define-compiler-macro
(func args
&rest body
)
2989 "Define a compiler-only macro.
2990 This is like `defmacro', but macro expansion occurs only if the call to
2991 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
2992 for optimizing the way calls to FUNC are compiled; the form returned by
2993 BODY should do the same thing as a call to the normal function called
2994 FUNC, though possibly more efficiently. Note that, like regular macros,
2995 compiler macros are expanded repeatedly until no further expansions are
2996 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
2997 original function call alone by declaring an initial `&whole foo' parameter
2998 and then returning foo."
2999 (declare (debug cl-defmacro
) (indent 2))
3000 (let ((p args
) (res nil
))
3001 (while (consp p
) (push (pop p
) res
))
3002 (setq args
(nconc (nreverse res
) (and p
(list '&rest p
)))))
3003 ;; FIXME: The code in bytecomp mishandles top-level expressions that define
3004 ;; uninterned functions. E.g. it would generate code like:
3005 ;; (defalias '#1=#:foo--cmacro #[514 ...])
3006 ;; (put 'foo 'compiler-macro '#:foo--cmacro)
3007 ;; So we circumvent this by using an interned name.
3008 (let ((fname (intern (concat (symbol-name func
) "--cmacro"))))
3010 ;; Name the compiler-macro function, so that `symbol-file' can find it.
3011 (cl-defun ,fname
,(if (memq '&whole args
) (delq '&whole args
)
3012 (cons '_cl-whole-arg args
))
3014 (put ',func
'compiler-macro
#',fname
))))
3017 (defun cl-compiler-macroexpand (form)
3018 "Like `macroexpand', but for compiler macros.
3019 Expands FORM repeatedly until no further expansion is possible.
3020 Returns FORM unchanged if it has no compiler macro, or if it has a
3021 macro that returns its `&whole' argument."
3023 (let ((func (car-safe form
)) (handler nil
))
3024 (while (and (symbolp func
)
3025 (not (setq handler
(get func
'compiler-macro
)))
3027 (or (not (autoloadp (symbol-function func
)))
3028 (autoload-do-load (symbol-function func
) func
)))
3029 (setq func
(symbol-function func
)))
3031 (not (eq form
(setq form
(apply handler form
(cdr form
))))))))
3034 ;; Optimize away unused block-wrappers.
3036 (defvar cl--active-block-names nil
)
3038 (cl-define-compiler-macro cl--block-wrapper
(cl-form)
3039 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form
)) nil
))
3040 (cl--active-block-names (cons cl-entry cl--active-block-names
))
3041 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
3042 (macroexp-progn (cddr cl-form
))
3043 macroexpand-all-environment
)))
3044 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
3045 ;; to indicate that this return value is already fully expanded.
3047 `(catch ,(nth 1 cl-form
) ,@(macroexp-unprogn cl-body
))
3050 (cl-define-compiler-macro cl--block-throw
(cl-tag cl-value
)
3051 (let ((cl-found (assq (nth 1 cl-tag
) cl--active-block-names
)))
3052 (if cl-found
(setcdr cl-found t
)))
3053 `(throw ,cl-tag
,cl-value
))
3055 ;; Compile-time optimizations for some functions defined in this package.
3057 (defun cl--compiler-macro-member (form a list
&rest keys
)
3058 (let ((test (and (= (length keys
) 2) (eq (car keys
) :test
)
3059 (cl--const-expr-val (nth 1 keys
)))))
3060 (cond ((eq test
'eq
) `(memq ,a
,list
))
3061 ((eq test
'equal
) `(member ,a
,list
))
3062 ((or (null keys
) (eq test
'eql
)) `(memql ,a
,list
))
3065 (defun cl--compiler-macro-assoc (form a list
&rest keys
)
3066 (let ((test (and (= (length keys
) 2) (eq (car keys
) :test
)
3067 (cl--const-expr-val (nth 1 keys
)))))
3068 (cond ((eq test
'eq
) `(assq ,a
,list
))
3069 ((eq test
'equal
) `(assoc ,a
,list
))
3070 ((and (macroexp-const-p a
) (or (null keys
) (eq test
'eql
)))
3071 (if (floatp (cl--const-expr-val a
))
3072 `(assoc ,a
,list
) `(assq ,a
,list
)))
3076 (defun cl--compiler-macro-adjoin (form a list
&rest keys
)
3077 (if (memq :key keys
) form
3078 (macroexp-let2* macroexp-copyable-p
((va a
) (vlist list
))
3079 `(if (cl-member ,va
,vlist
,@keys
) ,vlist
(cons ,va
,vlist
)))))
3081 (defun cl--compiler-macro-get (_form sym prop
&optional def
)
3083 `(cl-getf (symbol-plist ,sym
) ,prop
,def
)
3086 (dolist (y '(cl-first cl-second cl-third cl-fourth
3087 cl-fifth cl-sixth cl-seventh
3088 cl-eighth cl-ninth cl-tenth
3089 cl-rest cl-endp cl-plusp cl-minusp
3090 cl-caaar cl-caadr cl-cadar
3091 cl-caddr cl-cdaar cl-cdadr
3092 cl-cddar cl-cdddr cl-caaaar
3093 cl-caaadr cl-caadar cl-caaddr
3094 cl-cadaar cl-cadadr cl-caddar
3095 cl-cadddr cl-cdaaar cl-cdaadr
3096 cl-cdadar cl-cdaddr cl-cddaar
3097 cl-cddadr cl-cdddar cl-cddddr
))
3098 (put y
'side-effect-free t
))
3100 ;;; Things that are inline.
3101 (cl-proclaim '(inline cl-acons cl-map cl-concatenate cl-notany
3102 cl-notevery cl-revappend cl-nreconc gethash
))
3104 ;;; Things that are side-effect-free.
3105 (mapc (lambda (x) (function-put x
'side-effect-free t
))
3106 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd
3107 cl-lcm cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem
3108 cl-subseq cl-list-length cl-get cl-getf
))
3110 ;;; Things that are side-effect-and-error-free.
3111 (mapc (lambda (x) (function-put x
'side-effect-free
'error-free
))
3112 '(eql cl-list
* cl-subst cl-acons cl-equalp
3113 cl-random-state-p copy-tree cl-sublis
))
3115 ;;; Types and assertions.
3118 (defmacro cl-deftype
(name arglist
&rest body
)
3119 "Define NAME as a new data type.
3120 The type name can then be used in `cl-typecase', `cl-check-type', etc."
3121 (declare (debug cl-defmacro
) (doc-string 3) (indent 2))
3122 `(cl-eval-when (compile load eval
)
3123 (put ',name
'cl-deftype-handler
3124 (cl-function (lambda (&cl-defs
('*) ,@arglist
) ,@body
)))))
3126 (cl-deftype extended-char
() `(and character
(not base-char
)))
3128 ;;; Additional functions that we can now define because we've defined
3129 ;;; `cl-defsubst' and `cl-typep'.
3131 (define-inline cl-struct-slot-value
(struct-type slot-name inst
)
3132 "Return the value of slot SLOT-NAME in INST of STRUCT-TYPE.
3133 STRUCT and SLOT-NAME are symbols. INST is a structure instance."
3134 (declare (side-effect-free t
))
3135 (inline-letevals (struct-type slot-name inst
)
3138 (unless (cl-typep ,inst
,struct-type
)
3139 (signal 'wrong-type-argument
(list ,struct-type
,inst
)))
3140 ;; We could use `elt', but since the byte compiler will resolve the
3141 ;; branch below at compile time, it's more efficient to use the
3142 ;; type-specific accessor.
3143 (if (eq (cl-struct-sequence-type ,struct-type
) 'list
)
3144 (nth (cl-struct-slot-offset ,struct-type
,slot-name
) ,inst
)
3145 (aref ,inst
(cl-struct-slot-offset ,struct-type
,slot-name
)))))))
3147 (run-hooks 'cl-macs-load-hook
)
3150 ;; byte-compile-dynamic: t
3151 ;; generated-autoload-file: "cl-loaddefs.el"
3156 ;;; cl-macs.el ends here