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