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