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