Macro-expand interpreted code during load.
[emacs.git] / lisp / emacs-lisp / cl-macs.el
blobaba412cc8f5e095270bca871c4add2cedd571237
1 ;;; cl-macs.el --- Common Lisp macros -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 1993, 2001-2012 Free Software Foundation, Inc.
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Version: 2.02
7 ;; Keywords: extensions
8 ;; Package: emacs
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; These are extensions to Emacs Lisp that provide a degree of
28 ;; Common Lisp compatibility, beyond what is already built-in
29 ;; in Emacs Lisp.
31 ;; This package was written by Dave Gillespie; it is a complete
32 ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
34 ;; Bug reports, comments, and suggestions are welcome!
36 ;; This file contains the portions of the Common Lisp extensions
37 ;; package which should be autoloaded, but need only be present
38 ;; if the compiler or interpreter is used---this file is not
39 ;; necessary for executing compiled code.
41 ;; See cl.el for Change Log.
44 ;;; Code:
46 (require 'cl-lib)
47 (require 'macroexp)
48 ;; `gv' is required here because cl-macs can be loaded before loaddefs.el.
49 (require 'gv)
51 (defmacro cl-pop2 (place)
52 (declare (debug edebug-sexps))
53 `(prog1 (car (cdr ,place))
54 (setq ,place (cdr (cdr ,place)))))
56 (defvar cl-optimize-safety)
57 (defvar cl-optimize-speed)
59 ;;; Initialization.
61 ;; Place compiler macros at the beginning, otherwise uses of the corresponding
62 ;; functions can lead to recursive-loads that prevent the calls from
63 ;; being optimized.
65 ;;;###autoload
66 (defun cl--compiler-macro-list* (_form arg &rest others)
67 (let* ((args (reverse (cons arg others)))
68 (form (car args)))
69 (while (setq args (cdr args))
70 (setq form `(cons ,(car args) ,form)))
71 form))
73 ;;;###autoload
74 (defun cl--compiler-macro-cXXr (form x)
75 (let* ((head (car form))
76 (n (symbol-name (car form)))
77 (i (- (length n) 2)))
78 (if (not (string-match "c[ad]+r\\'" n))
79 (if (and (fboundp head) (symbolp (symbol-function head)))
80 (cl--compiler-macro-cXXr (cons (symbol-function head) (cdr form))
82 (error "Compiler macro for cXXr applied to non-cXXr form"))
83 (while (> i (match-beginning 0))
84 (setq x (list (if (eq (aref n i) ?a) 'car 'cdr) x))
85 (setq i (1- i)))
86 x)))
88 ;;; Some predicates for analyzing Lisp forms.
89 ;; These are used by various
90 ;; macro expanders to optimize the results in certain common cases.
92 (defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
93 car-safe cdr-safe progn prog1 prog2))
94 (defconst cl--safe-funcs '(* / % length memq list vector vectorp
95 < > <= >= = error))
97 (defun cl--simple-expr-p (x &optional size)
98 "Check if no side effects, and executes quickly."
99 (or size (setq size 10))
100 (if (and (consp x) (not (memq (car x) '(quote function cl-function))))
101 (and (symbolp (car x))
102 (or (memq (car x) cl--simple-funcs)
103 (get (car x) 'side-effect-free))
104 (progn
105 (setq size (1- size))
106 (while (and (setq x (cdr x))
107 (setq size (cl--simple-expr-p (car x) size))))
108 (and (null x) (>= size 0) size)))
109 (and (> size 0) (1- size))))
111 (defun cl--simple-exprs-p (xs)
112 (while (and xs (cl--simple-expr-p (car xs)))
113 (setq xs (cdr xs)))
114 (not xs))
116 (defun cl--safe-expr-p (x)
117 "Check if no side effects."
118 (or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
119 (and (symbolp (car x))
120 (or (memq (car x) cl--simple-funcs)
121 (memq (car x) cl--safe-funcs)
122 (get (car x) 'side-effect-free))
123 (progn
124 (while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
125 (null x)))))
127 ;;; Check if constant (i.e., no side effects or dependencies).
128 (defun cl--const-expr-p (x)
129 (cond ((consp x)
130 (or (eq (car x) 'quote)
131 (and (memq (car x) '(function cl-function))
132 (or (symbolp (nth 1 x))
133 (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
134 ((symbolp x) (and (memq x '(nil t)) t))
135 (t t)))
137 (defun cl--const-expr-val (x)
138 (and (macroexp-const-p x) (if (consp x) (nth 1 x) x)))
140 (defun cl--expr-contains (x y)
141 "Count number of times X refers to Y. Return nil for 0 times."
142 ;; FIXME: This is naive, and it will cl-count Y as referred twice in
143 ;; (let ((Y 1)) Y) even though it should be 0. Also it is often called on
144 ;; non-macroexpanded code, so it may also miss some occurrences that would
145 ;; only appear in the expanded code.
146 (cond ((equal y x) 1)
147 ((and (consp x) (not (memq (car x) '(quote function cl-function))))
148 (let ((sum 0))
149 (while (consp x)
150 (setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
151 (setq sum (+ sum (or (cl--expr-contains x y) 0)))
152 (and (> sum 0) sum)))
153 (t nil)))
155 (defun cl--expr-contains-any (x y)
156 (while (and y (not (cl--expr-contains x (car y)))) (pop y))
159 (defun cl--expr-depends-p (x y)
160 "Check whether X may depend on any of the symbols in Y."
161 (and (not (macroexp-const-p x))
162 (or (not (cl--safe-expr-p x)) (cl--expr-contains-any x y))))
164 ;;; Symbols.
166 (defvar cl--gensym-counter)
167 ;;;###autoload
168 (defun cl-gensym (&optional prefix)
169 "Generate a new uninterned symbol.
170 The name is made by appending a number to PREFIX, default \"G\"."
171 (let ((pfix (if (stringp prefix) prefix "G"))
172 (num (if (integerp prefix) prefix
173 (prog1 cl--gensym-counter
174 (setq cl--gensym-counter (1+ cl--gensym-counter))))))
175 (make-symbol (format "%s%d" pfix num))))
177 ;;;###autoload
178 (defun cl-gentemp (&optional prefix)
179 "Generate a new interned symbol with a unique name.
180 The name is made by appending a number to PREFIX, default \"G\"."
181 (let ((pfix (if (stringp prefix) prefix "G"))
182 name)
183 (while (intern-soft (setq name (format "%s%d" pfix cl--gensym-counter)))
184 (setq cl--gensym-counter (1+ cl--gensym-counter)))
185 (intern name)))
188 ;;; Program structure.
190 (def-edebug-spec cl-declarations
191 (&rest ("cl-declare" &rest sexp)))
193 (def-edebug-spec cl-declarations-or-string
194 (&or stringp cl-declarations))
196 (def-edebug-spec cl-lambda-list
197 (([&rest arg]
198 [&optional ["&optional" cl-&optional-arg &rest cl-&optional-arg]]
199 [&optional ["&rest" arg]]
200 [&optional ["&key" [cl-&key-arg &rest cl-&key-arg]
201 &optional "&allow-other-keys"]]
202 [&optional ["&aux" &rest
203 &or (symbolp &optional def-form) symbolp]]
206 (def-edebug-spec cl-&optional-arg
207 (&or (arg &optional def-form arg) arg))
209 (def-edebug-spec cl-&key-arg
210 (&or ([&or (symbolp arg) arg] &optional def-form arg) arg))
212 (defconst cl--lambda-list-keywords
213 '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
215 (defvar cl--bind-block) (defvar cl--bind-defs) (defvar cl--bind-enquote)
216 (defvar cl--bind-inits) (defvar cl--bind-lets) (defvar cl--bind-forms)
218 (defun cl--transform-lambda (form bind-block)
219 (let* ((args (car form)) (body (cdr form)) (orig-args args)
220 (cl--bind-block bind-block) (cl--bind-defs nil) (cl--bind-enquote nil)
221 (cl--bind-inits nil) (cl--bind-lets nil) (cl--bind-forms nil)
222 (header nil) (simple-args nil))
223 (while (or (stringp (car body))
224 (memq (car-safe (car body)) '(interactive cl-declare)))
225 (push (pop body) header))
226 (setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
227 (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
228 (if (setq cl--bind-defs (cadr (memq '&cl-defs args)))
229 (setq args (delq '&cl-defs (delq cl--bind-defs args))
230 cl--bind-defs (cadr cl--bind-defs)))
231 (if (setq cl--bind-enquote (memq '&cl-quote args))
232 (setq args (delq '&cl-quote args)))
233 (if (memq '&whole args) (error "&whole not currently implemented"))
234 (let* ((p (memq '&environment args)) (v (cadr p))
235 (env-exp 'macroexpand-all-environment))
236 (if p (setq args (nconc (delq (car p) (delq v args))
237 (list '&aux (list v env-exp))))))
238 (while (and args (symbolp (car args))
239 (not (memq (car args) '(nil &rest &body &key &aux)))
240 (not (and (eq (car args) '&optional)
241 (or cl--bind-defs (consp (cadr args))))))
242 (push (pop args) simple-args))
243 (or (eq cl--bind-block 'cl-none)
244 (setq body (list `(cl-block ,cl--bind-block ,@body))))
245 (if (null args)
246 (cl-list* nil (nreverse simple-args) (nconc (nreverse header) body))
247 (if (memq '&optional simple-args) (push '&optional args))
248 (cl--do-arglist args nil (- (length simple-args)
249 (if (memq '&optional simple-args) 1 0)))
250 (setq cl--bind-lets (nreverse cl--bind-lets))
251 (cl-list* (and cl--bind-inits `(cl-eval-when (compile load eval)
252 ,@(nreverse cl--bind-inits)))
253 (nconc (nreverse simple-args)
254 (list '&rest (car (pop cl--bind-lets))))
255 (nconc (let ((hdr (nreverse header)))
256 ;; Macro expansion can take place in the middle of
257 ;; apparently harmless computation, so it should not
258 ;; touch the match-data.
259 (save-match-data
260 (require 'help-fns)
261 (cons (help-add-fundoc-usage
262 (if (stringp (car hdr)) (pop hdr))
263 (format "%S"
264 (cons 'fn
265 (cl--make-usage-args orig-args))))
266 hdr)))
267 (list `(let* ,cl--bind-lets
268 ,@(nreverse cl--bind-forms)
269 ,@body)))))))
271 ;;;###autoload
272 (defmacro cl-defun (name args &rest body)
273 "Define NAME as a function.
274 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
275 and BODY is implicitly surrounded by (cl-block NAME ...).
277 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
278 (declare (debug
279 ;; Same as defun but use cl-lambda-list.
280 (&define [&or name ("setf" :name setf name)]
281 cl-lambda-list
282 cl-declarations-or-string
283 [&optional ("interactive" interactive)]
284 def-body))
285 (doc-string 3)
286 (indent 2))
287 (let* ((res (cl--transform-lambda (cons args body) name))
288 (form `(defun ,name ,@(cdr res))))
289 (if (car res) `(progn ,(car res) ,form) form)))
291 ;; The lambda list for macros is different from that of normal lambdas.
292 ;; Note that &environment is only allowed as first or last items in the
293 ;; top level list.
295 (def-edebug-spec cl-macro-list
296 (([&optional "&environment" arg]
297 [&rest cl-macro-arg]
298 [&optional ["&optional" &rest
299 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
300 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
301 [&optional ["&key" [&rest
302 [&or ([&or (symbolp cl-macro-arg) arg]
303 &optional def-form cl-macro-arg)
304 arg]]
305 &optional "&allow-other-keys"]]
306 [&optional ["&aux" &rest
307 &or (symbolp &optional def-form) symbolp]]
308 [&optional "&environment" arg]
311 (def-edebug-spec cl-macro-arg
312 (&or arg cl-macro-list1))
314 (def-edebug-spec cl-macro-list1
315 (([&optional "&whole" arg] ;; only allowed at lower levels
316 [&rest cl-macro-arg]
317 [&optional ["&optional" &rest
318 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
319 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
320 [&optional ["&key" [&rest
321 [&or ([&or (symbolp cl-macro-arg) arg]
322 &optional def-form cl-macro-arg)
323 arg]]
324 &optional "&allow-other-keys"]]
325 [&optional ["&aux" &rest
326 &or (symbolp &optional def-form) symbolp]]
327 . [&or arg nil])))
329 ;;;###autoload
330 (defmacro cl-defmacro (name args &rest body)
331 "Define NAME as a macro.
332 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
333 and BODY is implicitly surrounded by (cl-block NAME ...).
335 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
336 (declare (debug
337 (&define name cl-macro-list cl-declarations-or-string def-body))
338 (doc-string 3)
339 (indent 2))
340 (let* ((res (cl--transform-lambda (cons args body) name))
341 (form `(defmacro ,name ,@(cdr res))))
342 (if (car res) `(progn ,(car res) ,form) form)))
344 (def-edebug-spec cl-lambda-expr
345 (&define ("lambda" cl-lambda-list
346 ;;cl-declarations-or-string
347 ;;[&optional ("interactive" interactive)]
348 def-body)))
350 ;; Redefine function-form to also match cl-function
351 (def-edebug-spec function-form
352 ;; form at the end could also handle "function",
353 ;; but recognize it specially to avoid wrapping function forms.
354 (&or ([&or "quote" "function"] &or symbolp lambda-expr)
355 ("cl-function" cl-function)
356 form))
358 ;;;###autoload
359 (defmacro cl-function (func)
360 "Introduce a function.
361 Like normal `function', except that if argument is a lambda form,
362 its argument list allows full Common Lisp conventions."
363 (declare (debug (&or symbolp cl-lambda-expr)))
364 (if (eq (car-safe func) 'lambda)
365 (let* ((res (cl--transform-lambda (cdr func) 'cl-none))
366 (form `(function (lambda . ,(cdr res)))))
367 (if (car res) `(progn ,(car res) ,form) form))
368 `(function ,func)))
370 (declare-function help-add-fundoc-usage "help-fns" (docstring arglist))
372 (defun cl--make-usage-var (x)
373 "X can be a var or a (destructuring) lambda-list."
374 (cond
375 ((symbolp x) (make-symbol (upcase (symbol-name x))))
376 ((consp x) (cl--make-usage-args x))
377 (t x)))
379 (defun cl--make-usage-args (arglist)
380 (if (cdr-safe (last arglist)) ;Not a proper list.
381 (let* ((last (last arglist))
382 (tail (cdr last)))
383 (unwind-protect
384 (progn
385 (setcdr last nil)
386 (nconc (cl--make-usage-args arglist) (cl--make-usage-var tail)))
387 (setcdr last tail)))
388 ;; `orig-args' can contain &cl-defs (an internal
389 ;; CL thingy I don't understand), so remove it.
390 (let ((x (memq '&cl-defs arglist)))
391 (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
392 (let ((state nil))
393 (mapcar (lambda (x)
394 (cond
395 ((symbolp x)
396 (if (eq ?\& (aref (symbol-name x) 0))
397 (setq state x)
398 (make-symbol (upcase (symbol-name x)))))
399 ((not (consp x)) x)
400 ((memq state '(nil &rest)) (cl--make-usage-args x))
401 (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
402 (cl-list*
403 (if (and (consp (car x)) (eq state '&key))
404 (list (caar x) (cl--make-usage-var (nth 1 (car x))))
405 (cl--make-usage-var (car x)))
406 (nth 1 x) ;INITFORM.
407 (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
408 ))))
409 arglist))))
411 (defun cl--do-arglist (args expr &optional num) ; uses bind-*
412 (if (nlistp args)
413 (if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
414 (error "Invalid argument name: %s" args)
415 (push (list args expr) cl--bind-lets))
416 (setq args (cl-copy-list args))
417 (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
418 (let ((p (memq '&body args))) (if p (setcar p '&rest)))
419 (if (memq '&environment args) (error "&environment used incorrectly"))
420 (let ((save-args args)
421 (restarg (memq '&rest args))
422 (safety (if (cl--compiling-file) cl-optimize-safety 3))
423 (keys nil)
424 (laterarg nil) (exactarg nil) minarg)
425 (or num (setq num 0))
426 (if (listp (cadr restarg))
427 (setq restarg (make-symbol "--cl-rest--"))
428 (setq restarg (cadr restarg)))
429 (push (list restarg expr) cl--bind-lets)
430 (if (eq (car args) '&whole)
431 (push (list (cl-pop2 args) restarg) cl--bind-lets))
432 (let ((p args))
433 (setq minarg restarg)
434 (while (and p (not (memq (car p) cl--lambda-list-keywords)))
435 (or (eq p args) (setq minarg (list 'cdr minarg)))
436 (setq p (cdr p)))
437 (if (memq (car p) '(nil &aux))
438 (setq minarg `(= (length ,restarg)
439 ,(length (cl-ldiff args p)))
440 exactarg (not (eq args p)))))
441 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
442 (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
443 restarg)))
444 (cl--do-arglist
445 (pop args)
446 (if (or laterarg (= safety 0)) poparg
447 `(if ,minarg ,poparg
448 (signal 'wrong-number-of-arguments
449 (list ,(and (not (eq cl--bind-block 'cl-none))
450 `',cl--bind-block)
451 (length ,restarg)))))))
452 (setq num (1+ num) laterarg t))
453 (while (and (eq (car args) '&optional) (pop args))
454 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
455 (let ((arg (pop args)))
456 (or (consp arg) (setq arg (list arg)))
457 (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
458 (let ((def (if (cdr arg) (nth 1 arg)
459 (or (car cl--bind-defs)
460 (nth 1 (assq (car arg) cl--bind-defs)))))
461 (poparg `(pop ,restarg)))
462 (and def cl--bind-enquote (setq def `',def))
463 (cl--do-arglist (car arg)
464 (if def `(if ,restarg ,poparg ,def) poparg))
465 (setq num (1+ num))))))
466 (if (eq (car args) '&rest)
467 (let ((arg (cl-pop2 args)))
468 (if (consp arg) (cl--do-arglist arg restarg)))
469 (or (eq (car args) '&key) (= safety 0) exactarg
470 (push `(if ,restarg
471 (signal 'wrong-number-of-arguments
472 (list
473 ,(and (not (eq cl--bind-block 'cl-none))
474 `',cl--bind-block)
475 (+ ,num (length ,restarg)))))
476 cl--bind-forms)))
477 (while (and (eq (car args) '&key) (pop args))
478 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
479 (let ((arg (pop args)))
480 (or (consp arg) (setq arg (list arg)))
481 (let* ((karg (if (consp (car arg)) (caar arg)
482 (intern (format ":%s" (car arg)))))
483 (varg (if (consp (car arg)) (cl-cadar arg) (car arg)))
484 (def (if (cdr arg) (cadr arg)
485 (or (car cl--bind-defs) (cadr (assq varg cl--bind-defs)))))
486 (look `(memq ',karg ,restarg)))
487 (and def cl--bind-enquote (setq def `',def))
488 (if (cddr arg)
489 (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
490 (val `(car (cdr ,temp))))
491 (cl--do-arglist temp look)
492 (cl--do-arglist varg
493 `(if ,temp
494 (prog1 ,val (setq ,temp t))
495 ,def)))
496 (cl--do-arglist
497 varg
498 `(car (cdr ,(if (null def)
499 look
500 `(or ,look
501 ,(if (eq (cl--const-expr-p def) t)
502 `'(nil ,(cl--const-expr-val def))
503 `(list nil ,def))))))))
504 (push karg keys)))))
505 (setq keys (nreverse keys))
506 (or (and (eq (car args) '&allow-other-keys) (pop args))
507 (null keys) (= safety 0)
508 (let* ((var (make-symbol "--cl-keys--"))
509 (allow '(:allow-other-keys))
510 (check `(while ,var
511 (cond
512 ((memq (car ,var) ',(append keys allow))
513 (setq ,var (cdr (cdr ,var))))
514 ((car (cdr (memq (quote ,@allow) ,restarg)))
515 (setq ,var nil))
517 (error
518 ,(format "Keyword argument %%s not one of %s"
519 keys)
520 (car ,var)))))))
521 (push `(let ((,var ,restarg)) ,check) cl--bind-forms)))
522 (while (and (eq (car args) '&aux) (pop args))
523 (while (and args (not (memq (car args) cl--lambda-list-keywords)))
524 (if (consp (car args))
525 (if (and cl--bind-enquote (cl-cadar args))
526 (cl--do-arglist (caar args)
527 `',(cadr (pop args)))
528 (cl--do-arglist (caar args) (cadr (pop args))))
529 (cl--do-arglist (pop args) nil))))
530 (if args (error "Malformed argument list %s" save-args)))))
532 (defun cl--arglist-args (args)
533 (if (nlistp args) (list args)
534 (let ((res nil) (kind nil) arg)
535 (while (consp args)
536 (setq arg (pop args))
537 (if (memq arg cl--lambda-list-keywords) (setq kind arg)
538 (if (eq arg '&cl-defs) (pop args)
539 (and (consp arg) kind (setq arg (car arg)))
540 (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
541 (setq res (nconc res (cl--arglist-args arg))))))
542 (nconc res (and args (list args))))))
544 ;;;###autoload
545 (defmacro cl-destructuring-bind (args expr &rest body)
546 (declare (indent 2)
547 (debug (&define cl-macro-list def-form cl-declarations def-body)))
548 (let* ((cl--bind-lets nil) (cl--bind-forms nil) (cl--bind-inits nil)
549 (cl--bind-defs nil) (cl--bind-block 'cl-none) (cl--bind-enquote nil))
550 (cl--do-arglist (or args '(&aux)) expr)
551 (append '(progn) cl--bind-inits
552 (list `(let* ,(nreverse cl--bind-lets)
553 ,@(nreverse cl--bind-forms) ,@body)))))
556 ;;; The `cl-eval-when' form.
558 (defvar cl-not-toplevel nil)
560 ;;;###autoload
561 (defmacro cl-eval-when (when &rest body)
562 "Control when BODY is evaluated.
563 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
564 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
565 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
567 \(fn (WHEN...) BODY...)"
568 (declare (indent 1) (debug ((&rest &or "compile" "load" "eval") body)))
569 (if (and (fboundp 'cl--compiling-file) (cl--compiling-file)
570 (not cl-not-toplevel) (not (boundp 'for-effect))) ; horrible kludge
571 (let ((comp (or (memq 'compile when) (memq :compile-toplevel when)))
572 (cl-not-toplevel t))
573 (if (or (memq 'load when) (memq :load-toplevel when))
574 (if comp (cons 'progn (mapcar 'cl--compile-time-too body))
575 `(if nil nil ,@body))
576 (progn (if comp (eval (cons 'progn body))) nil)))
577 (and (or (memq 'eval when) (memq :execute when))
578 (cons 'progn body))))
580 (defun cl--compile-time-too (form)
581 (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
582 (setq form (macroexpand
583 form (cons '(cl-eval-when) byte-compile-macro-environment))))
584 (cond ((eq (car-safe form) 'progn)
585 (cons 'progn (mapcar 'cl--compile-time-too (cdr form))))
586 ((eq (car-safe form) 'cl-eval-when)
587 (let ((when (nth 1 form)))
588 (if (or (memq 'eval when) (memq :execute when))
589 `(cl-eval-when (compile ,@when) ,@(cddr form))
590 form)))
591 (t (eval form) form)))
593 ;;;###autoload
594 (defmacro cl-load-time-value (form &optional _read-only)
595 "Like `progn', but evaluates the body at load time.
596 The result of the body appears to the compiler as a quoted constant."
597 (declare (debug (form &optional sexp)))
598 (if (cl--compiling-file)
599 (let* ((temp (cl-gentemp "--cl-load-time--"))
600 (set `(set ',temp ,form)))
601 (if (and (fboundp 'byte-compile-file-form-defmumble)
602 (boundp 'this-kind) (boundp 'that-one))
603 (fset 'byte-compile-file-form
604 `(lambda (form)
605 (fset 'byte-compile-file-form
606 ',(symbol-function 'byte-compile-file-form))
607 (byte-compile-file-form ',set)
608 (byte-compile-file-form form)))
609 (print set (symbol-value 'byte-compile--outbuffer)))
610 `(symbol-value ',temp))
611 `',(eval form)))
614 ;;; Conditional control structures.
616 ;;;###autoload
617 (defmacro cl-case (expr &rest clauses)
618 "Eval EXPR and choose among clauses on that value.
619 Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
620 against each key in each KEYLIST; the corresponding BODY is evaluated.
621 If no clause succeeds, cl-case returns nil. A single atom may be used in
622 place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
623 allowed only in the final clause, and matches if no other keys match.
624 Key values are compared by `eql'.
625 \n(fn EXPR (KEYLIST BODY...)...)"
626 (declare (indent 1) (debug (form &rest (sexp body))))
627 (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
628 (head-list nil)
629 (body (cons
630 'cond
631 (mapcar
632 (function
633 (lambda (c)
634 (cons (cond ((memq (car c) '(t otherwise)) t)
635 ((eq (car c) 'cl--ecase-error-flag)
636 `(error "cl-ecase failed: %s, %s"
637 ,temp ',(reverse head-list)))
638 ((listp (car c))
639 (setq head-list (append (car c) head-list))
640 `(cl-member ,temp ',(car c)))
642 (if (memq (car c) head-list)
643 (error "Duplicate key in case: %s"
644 (car c)))
645 (push (car c) head-list)
646 `(eql ,temp ',(car c))))
647 (or (cdr c) '(nil)))))
648 clauses))))
649 (if (eq temp expr) body
650 `(let ((,temp ,expr)) ,body))))
652 ;;;###autoload
653 (defmacro cl-ecase (expr &rest clauses)
654 "Like `cl-case', but error if no case fits.
655 `otherwise'-clauses are not allowed.
656 \n(fn EXPR (KEYLIST BODY...)...)"
657 (declare (indent 1) (debug cl-case))
658 `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
660 ;;;###autoload
661 (defmacro cl-typecase (expr &rest clauses)
662 "Evals EXPR, chooses among clauses on that value.
663 Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
664 satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
665 cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
666 final clause, and matches if no other keys match.
667 \n(fn EXPR (TYPE BODY...)...)"
668 (declare (indent 1)
669 (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
670 (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
671 (type-list nil)
672 (body (cons
673 'cond
674 (mapcar
675 (function
676 (lambda (c)
677 (cons (cond ((eq (car c) 'otherwise) t)
678 ((eq (car c) 'cl--ecase-error-flag)
679 `(error "cl-etypecase failed: %s, %s"
680 ,temp ',(reverse type-list)))
682 (push (car c) type-list)
683 (cl--make-type-test temp (car c))))
684 (or (cdr c) '(nil)))))
685 clauses))))
686 (if (eq temp expr) body
687 `(let ((,temp ,expr)) ,body))))
689 ;;;###autoload
690 (defmacro cl-etypecase (expr &rest clauses)
691 "Like `cl-typecase', but error if no case fits.
692 `otherwise'-clauses are not allowed.
693 \n(fn EXPR (TYPE BODY...)...)"
694 (declare (indent 1) (debug cl-typecase))
695 `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
698 ;;; Blocks and exits.
700 ;;;###autoload
701 (defmacro cl-block (name &rest body)
702 "Define a lexically-scoped block named NAME.
703 NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
704 to jump prematurely out of the block. This differs from `catch' and `throw'
705 in two respects: First, the NAME is an unevaluated symbol rather than a
706 quoted symbol or other form; and second, NAME is lexically rather than
707 dynamically scoped: Only references to it within BODY will work. These
708 references may appear inside macro expansions, but not inside functions
709 called from BODY."
710 (declare (indent 1) (debug (symbolp body)))
711 (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
712 `(cl--block-wrapper
713 (catch ',(intern (format "--cl-block-%s--" name))
714 ,@body))))
716 ;;;###autoload
717 (defmacro cl-return (&optional result)
718 "Return from the block named nil.
719 This is equivalent to `(cl-return-from nil RESULT)'."
720 (declare (debug (&optional form)))
721 `(cl-return-from nil ,result))
723 ;;;###autoload
724 (defmacro cl-return-from (name &optional result)
725 "Return from the block named NAME.
726 This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
727 returning RESULT from that form (or nil if RESULT is omitted).
728 This is compatible with Common Lisp, but note that `defun' and
729 `defmacro' do not create implicit blocks as they do in Common Lisp."
730 (declare (indent 1) (debug (symbolp &optional form)))
731 (let ((name2 (intern (format "--cl-block-%s--" name))))
732 `(cl--block-throw ',name2 ,result)))
735 ;;; The "cl-loop" macro.
737 (defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
738 (defvar cl--loop-bindings) (defvar cl--loop-body) (defvar cl--loop-destr-temps)
739 (defvar cl--loop-finally) (defvar cl--loop-finish-flag)
740 (defvar cl--loop-first-flag)
741 (defvar cl--loop-initially) (defvar cl--loop-map-form) (defvar cl--loop-name)
742 (defvar cl--loop-result) (defvar cl--loop-result-explicit)
743 (defvar cl--loop-result-var) (defvar cl--loop-steps) (defvar cl--loop-symbol-macs)
745 ;;;###autoload
746 (defmacro cl-loop (&rest loop-args)
747 "The Common Lisp `cl-loop' macro.
748 Valid clauses are:
749 for VAR from/upfrom/downfrom NUM to/upto/downto/above/below NUM by NUM,
750 for VAR in LIST by FUNC, for VAR on LIST by FUNC, for VAR = INIT then EXPR,
751 for VAR across ARRAY, repeat NUM, with VAR = INIT, while COND, until COND,
752 always COND, never COND, thereis COND, collect EXPR into VAR,
753 append EXPR into VAR, nconc EXPR into VAR, sum EXPR into VAR,
754 count EXPR into VAR, maximize EXPR into VAR, minimize EXPR into VAR,
755 if COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
756 unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
757 do EXPRS..., initially EXPRS..., finally EXPRS..., return EXPR,
758 finally return EXPR, named NAME.
760 \(fn CLAUSE...)"
761 (declare (debug (&rest &or
762 ;; These are usually followed by a symbol, but it can
763 ;; actually be any destructuring-bind pattern, which
764 ;; would erroneously match `form'.
765 [[&or "for" "as" "with" "and"] sexp]
766 ;; These are followed by expressions which could
767 ;; erroneously match `symbolp'.
768 [[&or "from" "upfrom" "downfrom" "to" "upto" "downto"
769 "above" "below" "by" "in" "on" "=" "across"
770 "repeat" "while" "until" "always" "never"
771 "thereis" "collect" "append" "nconc" "sum"
772 "count" "maximize" "minimize" "if" "unless"
773 "return"] form]
774 ;; Simple default, which covers 99% of the cases.
775 symbolp form)))
776 (if (not (memq t (mapcar 'symbolp (delq nil (delq t (cl-copy-list loop-args))))))
777 `(cl-block nil (while t ,@loop-args))
778 (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
779 (cl--loop-body nil) (cl--loop-steps nil)
780 (cl--loop-result nil) (cl--loop-result-explicit nil)
781 (cl--loop-result-var nil) (cl--loop-finish-flag nil)
782 (cl--loop-accum-var nil) (cl--loop-accum-vars nil)
783 (cl--loop-initially nil) (cl--loop-finally nil)
784 (cl--loop-map-form nil) (cl--loop-first-flag nil)
785 (cl--loop-destr-temps nil) (cl--loop-symbol-macs nil))
786 (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
787 (while (not (eq (car cl--loop-args) 'cl-end-loop)) (cl-parse-loop-clause))
788 (if cl--loop-finish-flag
789 (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
790 (if cl--loop-first-flag
791 (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
792 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
793 (let* ((epilogue (nconc (nreverse cl--loop-finally)
794 (list (or cl--loop-result-explicit cl--loop-result))))
795 (ands (cl--loop-build-ands (nreverse cl--loop-body)))
796 (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
797 (body (append
798 (nreverse cl--loop-initially)
799 (list (if cl--loop-map-form
800 `(cl-block --cl-finish--
801 ,(cl-subst
802 (if (eq (car ands) t) while-body
803 (cons `(or ,(car ands)
804 (cl-return-from --cl-finish--
805 nil))
806 while-body))
807 '--cl-map cl--loop-map-form))
808 `(while ,(car ands) ,@while-body)))
809 (if cl--loop-finish-flag
810 (if (equal epilogue '(nil)) (list cl--loop-result-var)
811 `((if ,cl--loop-finish-flag
812 (progn ,@epilogue) ,cl--loop-result-var)))
813 epilogue))))
814 (if cl--loop-result-var (push (list cl--loop-result-var) cl--loop-bindings))
815 (while cl--loop-bindings
816 (if (cdar cl--loop-bindings)
817 (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
818 (let ((lets nil))
819 (while (and cl--loop-bindings
820 (not (cdar cl--loop-bindings)))
821 (push (car (pop cl--loop-bindings)) lets))
822 (setq body (list (cl--loop-let lets body nil))))))
823 (if cl--loop-symbol-macs
824 (setq body (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
825 `(cl-block ,cl--loop-name ,@body)))))
827 ;; Below is a complete spec for cl-loop, in several parts that correspond
828 ;; to the syntax given in CLtL2. The specs do more than specify where
829 ;; the forms are; it also specifies, as much as Edebug allows, all the
830 ;; syntactically valid cl-loop clauses. The disadvantage of this
831 ;; completeness is rigidity, but the "for ... being" clause allows
832 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
834 ;; (def-edebug-spec cl-loop
835 ;; ([&optional ["named" symbolp]]
836 ;; [&rest
837 ;; &or
838 ;; ["repeat" form]
839 ;; loop-for-as
840 ;; loop-with
841 ;; loop-initial-final]
842 ;; [&rest loop-clause]
843 ;; ))
845 ;; (def-edebug-spec loop-with
846 ;; ("with" loop-var
847 ;; loop-type-spec
848 ;; [&optional ["=" form]]
849 ;; &rest ["and" loop-var
850 ;; loop-type-spec
851 ;; [&optional ["=" form]]]))
853 ;; (def-edebug-spec loop-for-as
854 ;; ([&or "for" "as"] loop-for-as-subclause
855 ;; &rest ["and" loop-for-as-subclause]))
857 ;; (def-edebug-spec loop-for-as-subclause
858 ;; (loop-var
859 ;; loop-type-spec
860 ;; &or
861 ;; [[&or "in" "on" "in-ref" "across-ref"]
862 ;; form &optional ["by" function-form]]
864 ;; ["=" form &optional ["then" form]]
865 ;; ["across" form]
866 ;; ["being"
867 ;; [&or "the" "each"]
868 ;; &or
869 ;; [[&or "element" "elements"]
870 ;; [&or "of" "in" "of-ref"] form
871 ;; &optional "using" ["index" symbolp]];; is this right?
872 ;; [[&or "hash-key" "hash-keys"
873 ;; "hash-value" "hash-values"]
874 ;; [&or "of" "in"]
875 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
876 ;; "hash-key" "hash-keys"] sexp)]]
878 ;; [[&or "symbol" "present-symbol" "external-symbol"
879 ;; "symbols" "present-symbols" "external-symbols"]
880 ;; [&or "in" "of"] package-p]
882 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
883 ;; [[&or "frame" "frames"
884 ;; "screen" "screens"
885 ;; "buffer" "buffers"]]
887 ;; [[&or "window" "windows"]
888 ;; [&or "of" "in"] form]
890 ;; [[&or "overlay" "overlays"
891 ;; "extent" "extents"]
892 ;; [&or "of" "in"] form
893 ;; &optional [[&or "from" "to"] form]]
895 ;; [[&or "interval" "intervals"]
896 ;; [&or "in" "of"] form
897 ;; &optional [[&or "from" "to"] form]
898 ;; ["property" form]]
900 ;; [[&or "key-code" "key-codes"
901 ;; "key-seq" "key-seqs"
902 ;; "key-binding" "key-bindings"]
903 ;; [&or "in" "of"] form
904 ;; &optional ["using" ([&or "key-code" "key-codes"
905 ;; "key-seq" "key-seqs"
906 ;; "key-binding" "key-bindings"]
907 ;; sexp)]]
908 ;; ;; For arbitrary extensions, recognize anything else.
909 ;; [symbolp &rest &or symbolp form]
910 ;; ]
912 ;; ;; arithmetic - must be last since all parts are optional.
913 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
914 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
915 ;; [&optional ["by" form]]
916 ;; ]))
918 ;; (def-edebug-spec loop-initial-final
919 ;; (&or ["initially"
920 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
921 ;; &rest loop-non-atomic-expr]
922 ;; ["finally" &or
923 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
924 ;; ["return" form]]))
926 ;; (def-edebug-spec loop-and-clause
927 ;; (loop-clause &rest ["and" loop-clause]))
929 ;; (def-edebug-spec loop-clause
930 ;; (&or
931 ;; [[&or "while" "until" "always" "never" "thereis"] form]
933 ;; [[&or "collect" "collecting"
934 ;; "append" "appending"
935 ;; "nconc" "nconcing"
936 ;; "concat" "vconcat"] form
937 ;; [&optional ["into" loop-var]]]
939 ;; [[&or "count" "counting"
940 ;; "sum" "summing"
941 ;; "maximize" "maximizing"
942 ;; "minimize" "minimizing"] form
943 ;; [&optional ["into" loop-var]]
944 ;; loop-type-spec]
946 ;; [[&or "if" "when" "unless"]
947 ;; form loop-and-clause
948 ;; [&optional ["else" loop-and-clause]]
949 ;; [&optional "end"]]
951 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
953 ;; ["return" form]
954 ;; loop-initial-final
955 ;; ))
957 ;; (def-edebug-spec loop-non-atomic-expr
958 ;; ([&not atom] form))
960 ;; (def-edebug-spec loop-var
961 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
962 ;; ;; loop-var =>
963 ;; ;; (loop-var . [&or nil loop-var])
964 ;; ;; (symbolp . [&or nil loop-var])
965 ;; ;; (symbolp . loop-var)
966 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
967 ;; ;; (symbolp . (symbolp . loop-var))
968 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
969 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
971 ;; (def-edebug-spec loop-type-spec
972 ;; (&optional ["of-type" loop-d-type-spec]))
974 ;; (def-edebug-spec loop-d-type-spec
975 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
979 (defun cl-parse-loop-clause () ; uses loop-*
980 (let ((word (pop cl--loop-args))
981 (hash-types '(hash-key hash-keys hash-value hash-values))
982 (key-types '(key-code key-codes key-seq key-seqs
983 key-binding key-bindings)))
984 (cond
986 ((null cl--loop-args)
987 (error "Malformed `cl-loop' macro"))
989 ((eq word 'named)
990 (setq cl--loop-name (pop cl--loop-args)))
992 ((eq word 'initially)
993 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
994 (or (consp (car cl--loop-args)) (error "Syntax error on `initially' clause"))
995 (while (consp (car cl--loop-args))
996 (push (pop cl--loop-args) cl--loop-initially)))
998 ((eq word 'finally)
999 (if (eq (car cl--loop-args) 'return)
1000 (setq cl--loop-result-explicit (or (cl-pop2 cl--loop-args) '(quote nil)))
1001 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
1002 (or (consp (car cl--loop-args)) (error "Syntax error on `finally' clause"))
1003 (if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
1004 (setq cl--loop-result-explicit (or (nth 1 (pop cl--loop-args)) '(quote nil)))
1005 (while (consp (car cl--loop-args))
1006 (push (pop cl--loop-args) cl--loop-finally)))))
1008 ((memq word '(for as))
1009 (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
1010 (ands nil))
1011 (while
1012 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1013 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
1014 ;; these vars get added to the macro-environment.
1015 (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
1016 (setq word (pop cl--loop-args))
1017 (if (eq word 'being) (setq word (pop cl--loop-args)))
1018 (if (memq word '(the each)) (setq word (pop cl--loop-args)))
1019 (if (memq word '(buffer buffers))
1020 (setq word 'in cl--loop-args (cons '(buffer-list) cl--loop-args)))
1021 (cond
1023 ((memq word '(from downfrom upfrom to downto upto
1024 above below by))
1025 (push word cl--loop-args)
1026 (if (memq (car cl--loop-args) '(downto above))
1027 (error "Must specify `from' value for downward cl-loop"))
1028 (let* ((down (or (eq (car cl--loop-args) 'downfrom)
1029 (memq (cl-caddr cl--loop-args) '(downto above))))
1030 (excl (or (memq (car cl--loop-args) '(above below))
1031 (memq (cl-caddr cl--loop-args) '(above below))))
1032 (start (and (memq (car cl--loop-args) '(from upfrom downfrom))
1033 (cl-pop2 cl--loop-args)))
1034 (end (and (memq (car cl--loop-args)
1035 '(to upto downto above below))
1036 (cl-pop2 cl--loop-args)))
1037 (step (and (eq (car cl--loop-args) 'by) (cl-pop2 cl--loop-args)))
1038 (end-var (and (not (macroexp-const-p end))
1039 (make-symbol "--cl-var--")))
1040 (step-var (and (not (macroexp-const-p step))
1041 (make-symbol "--cl-var--"))))
1042 (and step (numberp step) (<= step 0)
1043 (error "Loop `by' value is not positive: %s" step))
1044 (push (list var (or start 0)) loop-for-bindings)
1045 (if end-var (push (list end-var end) loop-for-bindings))
1046 (if step-var (push (list step-var step)
1047 loop-for-bindings))
1048 (if end
1049 (push (list
1050 (if down (if excl '> '>=) (if excl '< '<=))
1051 var (or end-var end)) cl--loop-body))
1052 (push (list var (list (if down '- '+) var
1053 (or step-var step 1)))
1054 loop-for-steps)))
1056 ((memq word '(in in-ref on))
1057 (let* ((on (eq word 'on))
1058 (temp (if (and on (symbolp var))
1059 var (make-symbol "--cl-var--"))))
1060 (push (list temp (pop cl--loop-args)) loop-for-bindings)
1061 (push `(consp ,temp) cl--loop-body)
1062 (if (eq word 'in-ref)
1063 (push (list var `(car ,temp)) cl--loop-symbol-macs)
1064 (or (eq temp var)
1065 (progn
1066 (push (list var nil) loop-for-bindings)
1067 (push (list var (if on temp `(car ,temp)))
1068 loop-for-sets))))
1069 (push (list temp
1070 (if (eq (car cl--loop-args) 'by)
1071 (let ((step (cl-pop2 cl--loop-args)))
1072 (if (and (memq (car-safe step)
1073 '(quote function
1074 cl-function))
1075 (symbolp (nth 1 step)))
1076 (list (nth 1 step) temp)
1077 `(funcall ,step ,temp)))
1078 `(cdr ,temp)))
1079 loop-for-steps)))
1081 ((eq word '=)
1082 (let* ((start (pop cl--loop-args))
1083 (then (if (eq (car cl--loop-args) 'then) (cl-pop2 cl--loop-args) start)))
1084 (push (list var nil) loop-for-bindings)
1085 (if (or ands (eq (car cl--loop-args) 'and))
1086 (progn
1087 (push `(,var
1088 (if ,(or cl--loop-first-flag
1089 (setq cl--loop-first-flag
1090 (make-symbol "--cl-var--")))
1091 ,start ,var))
1092 loop-for-sets)
1093 (push (list var then) loop-for-steps))
1094 (push (list var
1095 (if (eq start then) start
1096 `(if ,(or cl--loop-first-flag
1097 (setq cl--loop-first-flag
1098 (make-symbol "--cl-var--")))
1099 ,start ,then)))
1100 loop-for-sets))))
1102 ((memq word '(across across-ref))
1103 (let ((temp-vec (make-symbol "--cl-vec--"))
1104 (temp-idx (make-symbol "--cl-idx--")))
1105 (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
1106 (push (list temp-idx -1) loop-for-bindings)
1107 (push `(< (setq ,temp-idx (1+ ,temp-idx))
1108 (length ,temp-vec)) cl--loop-body)
1109 (if (eq word 'across-ref)
1110 (push (list var `(aref ,temp-vec ,temp-idx))
1111 cl--loop-symbol-macs)
1112 (push (list var nil) loop-for-bindings)
1113 (push (list var `(aref ,temp-vec ,temp-idx))
1114 loop-for-sets))))
1116 ((memq word '(element elements))
1117 (let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
1118 (and (not (memq (car cl--loop-args) '(in of)))
1119 (error "Expected `of'"))))
1120 (seq (cl-pop2 cl--loop-args))
1121 (temp-seq (make-symbol "--cl-seq--"))
1122 (temp-idx (if (eq (car cl--loop-args) 'using)
1123 (if (and (= (length (cadr cl--loop-args)) 2)
1124 (eq (cl-caadr cl--loop-args) 'index))
1125 (cadr (cl-pop2 cl--loop-args))
1126 (error "Bad `using' clause"))
1127 (make-symbol "--cl-idx--"))))
1128 (push (list temp-seq seq) loop-for-bindings)
1129 (push (list temp-idx 0) loop-for-bindings)
1130 (if ref
1131 (let ((temp-len (make-symbol "--cl-len--")))
1132 (push (list temp-len `(length ,temp-seq))
1133 loop-for-bindings)
1134 (push (list var `(elt ,temp-seq ,temp-idx))
1135 cl--loop-symbol-macs)
1136 (push `(< ,temp-idx ,temp-len) cl--loop-body))
1137 (push (list var nil) loop-for-bindings)
1138 (push `(and ,temp-seq
1139 (or (consp ,temp-seq)
1140 (< ,temp-idx (length ,temp-seq))))
1141 cl--loop-body)
1142 (push (list var `(if (consp ,temp-seq)
1143 (pop ,temp-seq)
1144 (aref ,temp-seq ,temp-idx)))
1145 loop-for-sets))
1146 (push (list temp-idx `(1+ ,temp-idx))
1147 loop-for-steps)))
1149 ((memq word hash-types)
1150 (or (memq (car cl--loop-args) '(in of)) (error "Expected `of'"))
1151 (let* ((table (cl-pop2 cl--loop-args))
1152 (other (if (eq (car cl--loop-args) 'using)
1153 (if (and (= (length (cadr cl--loop-args)) 2)
1154 (memq (cl-caadr cl--loop-args) hash-types)
1155 (not (eq (cl-caadr cl--loop-args) word)))
1156 (cadr (cl-pop2 cl--loop-args))
1157 (error "Bad `using' clause"))
1158 (make-symbol "--cl-var--"))))
1159 (if (memq word '(hash-value hash-values))
1160 (setq var (prog1 other (setq other var))))
1161 (setq cl--loop-map-form
1162 `(maphash (lambda (,var ,other) . --cl-map) ,table))))
1164 ((memq word '(symbol present-symbol external-symbol
1165 symbols present-symbols external-symbols))
1166 (let ((ob (and (memq (car cl--loop-args) '(in of)) (cl-pop2 cl--loop-args))))
1167 (setq cl--loop-map-form
1168 `(mapatoms (lambda (,var) . --cl-map) ,ob))))
1170 ((memq word '(overlay overlays extent extents))
1171 (let ((buf nil) (from nil) (to nil))
1172 (while (memq (car cl--loop-args) '(in of from to))
1173 (cond ((eq (car cl--loop-args) 'from) (setq from (cl-pop2 cl--loop-args)))
1174 ((eq (car cl--loop-args) 'to) (setq to (cl-pop2 cl--loop-args)))
1175 (t (setq buf (cl-pop2 cl--loop-args)))))
1176 (setq cl--loop-map-form
1177 `(cl--map-overlays
1178 (lambda (,var ,(make-symbol "--cl-var--"))
1179 (progn . --cl-map) nil)
1180 ,buf ,from ,to))))
1182 ((memq word '(interval intervals))
1183 (let ((buf nil) (prop nil) (from nil) (to nil)
1184 (var1 (make-symbol "--cl-var1--"))
1185 (var2 (make-symbol "--cl-var2--")))
1186 (while (memq (car cl--loop-args) '(in of property from to))
1187 (cond ((eq (car cl--loop-args) 'from) (setq from (cl-pop2 cl--loop-args)))
1188 ((eq (car cl--loop-args) 'to) (setq to (cl-pop2 cl--loop-args)))
1189 ((eq (car cl--loop-args) 'property)
1190 (setq prop (cl-pop2 cl--loop-args)))
1191 (t (setq buf (cl-pop2 cl--loop-args)))))
1192 (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
1193 (setq var1 (car var) var2 (cdr var))
1194 (push (list var `(cons ,var1 ,var2)) loop-for-sets))
1195 (setq cl--loop-map-form
1196 `(cl--map-intervals
1197 (lambda (,var1 ,var2) . --cl-map)
1198 ,buf ,prop ,from ,to))))
1200 ((memq word key-types)
1201 (or (memq (car cl--loop-args) '(in of)) (error "Expected `of'"))
1202 (let ((cl-map (cl-pop2 cl--loop-args))
1203 (other (if (eq (car cl--loop-args) 'using)
1204 (if (and (= (length (cadr cl--loop-args)) 2)
1205 (memq (cl-caadr cl--loop-args) key-types)
1206 (not (eq (cl-caadr cl--loop-args) word)))
1207 (cadr (cl-pop2 cl--loop-args))
1208 (error "Bad `using' clause"))
1209 (make-symbol "--cl-var--"))))
1210 (if (memq word '(key-binding key-bindings))
1211 (setq var (prog1 other (setq other var))))
1212 (setq cl--loop-map-form
1213 `(,(if (memq word '(key-seq key-seqs))
1214 'cl--map-keymap-recursively 'map-keymap)
1215 (lambda (,var ,other) . --cl-map) ,cl-map))))
1217 ((memq word '(frame frames screen screens))
1218 (let ((temp (make-symbol "--cl-var--")))
1219 (push (list var '(selected-frame))
1220 loop-for-bindings)
1221 (push (list temp nil) loop-for-bindings)
1222 (push `(prog1 (not (eq ,var ,temp))
1223 (or ,temp (setq ,temp ,var)))
1224 cl--loop-body)
1225 (push (list var `(next-frame ,var))
1226 loop-for-steps)))
1228 ((memq word '(window windows))
1229 (let ((scr (and (memq (car cl--loop-args) '(in of)) (cl-pop2 cl--loop-args)))
1230 (temp (make-symbol "--cl-var--"))
1231 (minip (make-symbol "--cl-minip--")))
1232 (push (list var (if scr
1233 `(frame-selected-window ,scr)
1234 '(selected-window)))
1235 loop-for-bindings)
1236 ;; If we started in the minibuffer, we need to
1237 ;; ensure that next-window will bring us back there
1238 ;; at some point. (Bug#7492).
1239 ;; (Consider using walk-windows instead of cl-loop if
1240 ;; you care about such things.)
1241 (push (list minip `(minibufferp (window-buffer ,var)))
1242 loop-for-bindings)
1243 (push (list temp nil) loop-for-bindings)
1244 (push `(prog1 (not (eq ,var ,temp))
1245 (or ,temp (setq ,temp ,var)))
1246 cl--loop-body)
1247 (push (list var `(next-window ,var ,minip))
1248 loop-for-steps)))
1251 (let ((handler (and (symbolp word)
1252 (get word 'cl--loop-for-handler))))
1253 (if handler
1254 (funcall handler var)
1255 (error "Expected a `for' preposition, found %s" word)))))
1256 (eq (car cl--loop-args) 'and))
1257 (setq ands t)
1258 (pop cl--loop-args))
1259 (if (and ands loop-for-bindings)
1260 (push (nreverse loop-for-bindings) cl--loop-bindings)
1261 (setq cl--loop-bindings (nconc (mapcar 'list loop-for-bindings)
1262 cl--loop-bindings)))
1263 (if loop-for-sets
1264 (push `(progn
1265 ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
1266 t) cl--loop-body))
1267 (if loop-for-steps
1268 (push (cons (if ands 'cl-psetq 'setq)
1269 (apply 'append (nreverse loop-for-steps)))
1270 cl--loop-steps))))
1272 ((eq word 'repeat)
1273 (let ((temp (make-symbol "--cl-var--")))
1274 (push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
1275 (push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
1277 ((memq word '(collect collecting))
1278 (let ((what (pop cl--loop-args))
1279 (var (cl--loop-handle-accum nil 'nreverse)))
1280 (if (eq var cl--loop-accum-var)
1281 (push `(progn (push ,what ,var) t) cl--loop-body)
1282 (push `(progn
1283 (setq ,var (nconc ,var (list ,what)))
1284 t) cl--loop-body))))
1286 ((memq word '(nconc nconcing append appending))
1287 (let ((what (pop cl--loop-args))
1288 (var (cl--loop-handle-accum nil 'nreverse)))
1289 (push `(progn
1290 (setq ,var
1291 ,(if (eq var cl--loop-accum-var)
1292 `(nconc
1293 (,(if (memq word '(nconc nconcing))
1294 #'nreverse #'reverse)
1295 ,what)
1296 ,var)
1297 `(,(if (memq word '(nconc nconcing))
1298 #'nconc #'append)
1299 ,var ,what))) t) cl--loop-body)))
1301 ((memq word '(concat concating))
1302 (let ((what (pop cl--loop-args))
1303 (var (cl--loop-handle-accum "")))
1304 (push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
1306 ((memq word '(vconcat vconcating))
1307 (let ((what (pop cl--loop-args))
1308 (var (cl--loop-handle-accum [])))
1309 (push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
1311 ((memq word '(sum summing))
1312 (let ((what (pop cl--loop-args))
1313 (var (cl--loop-handle-accum 0)))
1314 (push `(progn (cl-incf ,var ,what) t) cl--loop-body)))
1316 ((memq word '(count counting))
1317 (let ((what (pop cl--loop-args))
1318 (var (cl--loop-handle-accum 0)))
1319 (push `(progn (if ,what (cl-incf ,var)) t) cl--loop-body)))
1321 ((memq word '(minimize minimizing maximize maximizing))
1322 (let* ((what (pop cl--loop-args))
1323 (temp (if (cl--simple-expr-p what) what (make-symbol "--cl-var--")))
1324 (var (cl--loop-handle-accum nil))
1325 (func (intern (substring (symbol-name word) 0 3)))
1326 (set `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
1327 (push `(progn ,(if (eq temp what) set
1328 `(let ((,temp ,what)) ,set))
1329 t) cl--loop-body)))
1331 ((eq word 'with)
1332 (let ((bindings nil))
1333 (while (progn (push (list (pop cl--loop-args)
1334 (and (eq (car cl--loop-args) '=) (cl-pop2 cl--loop-args)))
1335 bindings)
1336 (eq (car cl--loop-args) 'and))
1337 (pop cl--loop-args))
1338 (push (nreverse bindings) cl--loop-bindings)))
1340 ((eq word 'while)
1341 (push (pop cl--loop-args) cl--loop-body))
1343 ((eq word 'until)
1344 (push `(not ,(pop cl--loop-args)) cl--loop-body))
1346 ((eq word 'always)
1347 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1348 (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
1349 (setq cl--loop-result t))
1351 ((eq word 'never)
1352 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1353 (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
1354 cl--loop-body)
1355 (setq cl--loop-result t))
1357 ((eq word 'thereis)
1358 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1359 (or cl--loop-result-var (setq cl--loop-result-var (make-symbol "--cl-var--")))
1360 (push `(setq ,cl--loop-finish-flag
1361 (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
1362 cl--loop-body))
1364 ((memq word '(if when unless))
1365 (let* ((cond (pop cl--loop-args))
1366 (then (let ((cl--loop-body nil))
1367 (cl-parse-loop-clause)
1368 (cl--loop-build-ands (nreverse cl--loop-body))))
1369 (else (let ((cl--loop-body nil))
1370 (if (eq (car cl--loop-args) 'else)
1371 (progn (pop cl--loop-args) (cl-parse-loop-clause)))
1372 (cl--loop-build-ands (nreverse cl--loop-body))))
1373 (simple (and (eq (car then) t) (eq (car else) t))))
1374 (if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
1375 (if (eq word 'unless) (setq then (prog1 else (setq else then))))
1376 (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
1377 (if simple (nth 1 else) (list (nth 2 else))))))
1378 (if (cl--expr-contains form 'it)
1379 (let ((temp (make-symbol "--cl-var--")))
1380 (push (list temp) cl--loop-bindings)
1381 (setq form `(if (setq ,temp ,cond)
1382 ,@(cl-subst temp 'it form))))
1383 (setq form `(if ,cond ,@form)))
1384 (push (if simple `(progn ,form t) form) cl--loop-body))))
1386 ((memq word '(do doing))
1387 (let ((body nil))
1388 (or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
1389 (while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
1390 (push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
1392 ((eq word 'return)
1393 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
1394 (or cl--loop-result-var (setq cl--loop-result-var (make-symbol "--cl-var--")))
1395 (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
1396 ,cl--loop-finish-flag nil) cl--loop-body))
1399 (let ((handler (and (symbolp word) (get word 'cl--loop-handler))))
1400 (or handler (error "Expected a cl-loop keyword, found %s" word))
1401 (funcall handler))))
1402 (if (eq (car cl--loop-args) 'and)
1403 (progn (pop cl--loop-args) (cl-parse-loop-clause)))))
1405 (defun cl--loop-let (specs body par) ; uses loop-*
1406 (let ((p specs) (temps nil) (new nil))
1407 (while (and p (or (symbolp (car-safe (car p))) (null (cl-cadar p))))
1408 (setq p (cdr p)))
1409 (and par p
1410 (progn
1411 (setq par nil p specs)
1412 (while p
1413 (or (macroexp-const-p (cl-cadar p))
1414 (let ((temp (make-symbol "--cl-var--")))
1415 (push (list temp (cl-cadar p)) temps)
1416 (setcar (cdar p) temp)))
1417 (setq p (cdr p)))))
1418 (while specs
1419 (if (and (consp (car specs)) (listp (caar specs)))
1420 (let* ((spec (caar specs)) (nspecs nil)
1421 (expr (cadr (pop specs)))
1422 (temp (cdr (or (assq spec cl--loop-destr-temps)
1423 (car (push (cons spec (or (last spec 0)
1424 (make-symbol "--cl-var--")))
1425 cl--loop-destr-temps))))))
1426 (push (list temp expr) new)
1427 (while (consp spec)
1428 (push (list (pop spec)
1429 (and expr (list (if spec 'pop 'car) temp)))
1430 nspecs))
1431 (setq specs (nconc (nreverse nspecs) specs)))
1432 (push (pop specs) new)))
1433 (if (eq body 'setq)
1434 (let ((set (cons (if par 'cl-psetq 'setq) (apply 'nconc (nreverse new)))))
1435 (if temps `(let* ,(nreverse temps) ,set) set))
1436 `(,(if par 'let 'let*)
1437 ,(nconc (nreverse temps) (nreverse new)) ,@body))))
1439 (defun cl--loop-handle-accum (def &optional func) ; uses loop-*
1440 (if (eq (car cl--loop-args) 'into)
1441 (let ((var (cl-pop2 cl--loop-args)))
1442 (or (memq var cl--loop-accum-vars)
1443 (progn (push (list (list var def)) cl--loop-bindings)
1444 (push var cl--loop-accum-vars)))
1445 var)
1446 (or cl--loop-accum-var
1447 (progn
1448 (push (list (list (setq cl--loop-accum-var (make-symbol "--cl-var--")) def))
1449 cl--loop-bindings)
1450 (setq cl--loop-result (if func (list func cl--loop-accum-var)
1451 cl--loop-accum-var))
1452 cl--loop-accum-var))))
1454 (defun cl--loop-build-ands (clauses)
1455 (let ((ands nil)
1456 (body nil))
1457 (while clauses
1458 (if (and (eq (car-safe (car clauses)) 'progn)
1459 (eq (car (last (car clauses))) t))
1460 (if (cdr clauses)
1461 (setq clauses (cons (nconc (butlast (car clauses))
1462 (if (eq (car-safe (cadr clauses))
1463 'progn)
1464 (cl-cdadr clauses)
1465 (list (cadr clauses))))
1466 (cddr clauses)))
1467 (setq body (cdr (butlast (pop clauses)))))
1468 (push (pop clauses) ands)))
1469 (setq ands (or (nreverse ands) (list t)))
1470 (list (if (cdr ands) (cons 'and ands) (car ands))
1471 body
1472 (let ((full (if body
1473 (append ands (list (cons 'progn (append body '(t)))))
1474 ands)))
1475 (if (cdr full) (cons 'and full) (car full))))))
1478 ;;; Other iteration control structures.
1480 ;;;###autoload
1481 (defmacro cl-do (steps endtest &rest body)
1482 "The Common Lisp `cl-do' loop.
1484 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1485 (declare (indent 2)
1486 (debug
1487 ((&rest &or symbolp (symbolp &optional form form))
1488 (form body)
1489 cl-declarations body)))
1490 (cl-expand-do-loop steps endtest body nil))
1492 ;;;###autoload
1493 (defmacro cl-do* (steps endtest &rest body)
1494 "The Common Lisp `cl-do*' loop.
1496 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1497 (declare (indent 2) (debug cl-do))
1498 (cl-expand-do-loop steps endtest body t))
1500 (defun cl-expand-do-loop (steps endtest body star)
1501 `(cl-block nil
1502 (,(if star 'let* 'let)
1503 ,(mapcar (lambda (c) (if (consp c) (list (car c) (nth 1 c)) c))
1504 steps)
1505 (while (not ,(car endtest))
1506 ,@body
1507 ,@(let ((sets (mapcar (lambda (c)
1508 (and (consp c) (cdr (cdr c))
1509 (list (car c) (nth 2 c))))
1510 steps)))
1511 (setq sets (delq nil sets))
1512 (and sets
1513 (list (cons (if (or star (not (cdr sets)))
1514 'setq 'cl-psetq)
1515 (apply 'append sets))))))
1516 ,@(or (cdr endtest) '(nil)))))
1518 ;;;###autoload
1519 (defmacro cl-dolist (spec &rest body)
1520 "Loop over a list.
1521 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1522 Then evaluate RESULT to get return value, default nil.
1523 An implicit nil block is established around the loop.
1525 \(fn (VAR LIST [RESULT]) BODY...)"
1526 (declare (debug ((symbolp form &optional form) cl-declarations body))
1527 (indent 1))
1528 `(cl-block nil
1529 (,(if (eq 'cl-dolist (symbol-function 'dolist)) 'cl--dolist 'dolist)
1530 ,spec ,@body)))
1532 ;;;###autoload
1533 (defmacro cl-dotimes (spec &rest body)
1534 "Loop a certain number of times.
1535 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1536 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1537 nil.
1539 \(fn (VAR COUNT [RESULT]) BODY...)"
1540 (declare (debug cl-dolist) (indent 1))
1541 `(cl-block nil
1542 (,(if (eq 'cl-dotimes (symbol-function 'dotimes)) 'cl--dotimes 'dotimes)
1543 ,spec ,@body)))
1545 ;;;###autoload
1546 (defmacro cl-do-symbols (spec &rest body)
1547 "Loop over all symbols.
1548 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1549 from OBARRAY.
1551 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1552 (declare (indent 1)
1553 (debug ((symbolp &optional form form) cl-declarations body)))
1554 ;; Apparently this doesn't have an implicit block.
1555 `(cl-block nil
1556 (let (,(car spec))
1557 (mapatoms #'(lambda (,(car spec)) ,@body)
1558 ,@(and (cadr spec) (list (cadr spec))))
1559 ,(cl-caddr spec))))
1561 ;;;###autoload
1562 (defmacro cl-do-all-symbols (spec &rest body)
1563 (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
1564 `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
1567 ;;; Assignments.
1569 ;;;###autoload
1570 (defmacro cl-psetq (&rest args)
1571 "Set SYMs to the values VALs in parallel.
1572 This is like `setq', except that all VAL forms are evaluated (in order)
1573 before assigning any symbols SYM to the corresponding values.
1575 \(fn SYM VAL SYM VAL ...)"
1576 (declare (debug setq))
1577 (cons 'cl-psetf args))
1580 ;;; Binding control structures.
1582 ;;;###autoload
1583 (defmacro cl-progv (symbols values &rest body)
1584 "Bind SYMBOLS to VALUES dynamically in BODY.
1585 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1586 Each symbol in the first list is bound to the corresponding value in the
1587 second list (or made unbound if VALUES is shorter than SYMBOLS); then the
1588 BODY forms are executed and their result is returned. This is much like
1589 a `let' form, except that the list of symbols can be computed at run-time."
1590 (declare (indent 2) (debug (form form body)))
1591 (let ((bodyfun (make-symbol "cl--progv-body"))
1592 (binds (make-symbol "binds"))
1593 (syms (make-symbol "syms"))
1594 (vals (make-symbol "vals")))
1595 `(progn
1596 (defvar ,bodyfun)
1597 (let* ((,syms ,symbols)
1598 (,vals ,values)
1599 (,bodyfun (lambda () ,@body))
1600 (,binds ()))
1601 (while ,syms
1602 (push (list (pop ,syms) (list 'quote (pop ,vals))) ,binds))
1603 (eval (list 'let ,binds '(funcall ,bodyfun)))))))
1605 (defvar cl--labels-convert-cache nil)
1607 (defun cl--labels-convert (f)
1608 "Special macro-expander to rename (function F) references in `cl-labels'."
1609 (cond
1610 ;; ¡¡Big Ugly Hack!! We can't use a compiler-macro because those are checked
1611 ;; *after* handling `function', but we want to stop macroexpansion from
1612 ;; being applied infinitely, so we use a cache to return the exact `form'
1613 ;; being expanded even though we don't receive it.
1614 ((eq f (car cl--labels-convert-cache)) (cdr cl--labels-convert-cache))
1616 (let ((found (assq f macroexpand-all-environment)))
1617 (if (and found (ignore-errors
1618 (eq (cadr (cl-caddr found)) 'cl-labels-args)))
1619 (cadr (cl-caddr (cl-cadddr found)))
1620 (let ((res `(function ,f)))
1621 (setq cl--labels-convert-cache (cons f res))
1622 res))))))
1624 ;;;###autoload
1625 (defmacro cl-flet (bindings &rest body)
1626 "Make temporary function definitions.
1627 Like `cl-labels' but the definitions are not recursive.
1629 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1630 (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
1631 (let ((binds ()) (newenv macroexpand-all-environment))
1632 (dolist (binding bindings)
1633 (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
1634 (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
1635 (push (cons (car binding)
1636 `(lambda (&rest cl-labels-args)
1637 (cl-list* 'funcall ',var
1638 cl-labels-args)))
1639 newenv)))
1640 `(let ,(nreverse binds)
1641 ,@(macroexp-unprogn
1642 (macroexpand-all
1643 `(progn ,@body)
1644 ;; Don't override lexical-let's macro-expander.
1645 (if (assq 'function newenv) newenv
1646 (cons (cons 'function #'cl--labels-convert) newenv)))))))
1648 ;;;###autoload
1649 (defmacro cl-flet* (bindings &rest body)
1650 "Make temporary function definitions.
1651 Like `cl-flet' but the definitions can refer to previous ones.
1653 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1654 (declare (indent 1) (debug cl-flet))
1655 (cond
1656 ((null bindings) (macroexp-progn body))
1657 ((null (cdr bindings)) `(cl-flet ,bindings ,@body))
1658 (t `(cl-flet (,(pop bindings)) (cl-flet* ,bindings ,@body)))))
1660 ;;;###autoload
1661 (defmacro cl-labels (bindings &rest body)
1662 "Make temporary function bindings.
1663 The bindings can be recursive and the scoping is lexical, but capturing them
1664 in closures will only work if `lexical-binding' is in use.
1666 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1667 (declare (indent 1) (debug cl-flet))
1668 (let ((binds ()) (newenv macroexpand-all-environment))
1669 (dolist (binding bindings)
1670 (let ((var (make-symbol (format "--cl-%s--" (car binding)))))
1671 (push (list var `(cl-function (lambda . ,(cdr binding)))) binds)
1672 (push (cons (car binding)
1673 `(lambda (&rest cl-labels-args)
1674 (cl-list* 'funcall ',var
1675 cl-labels-args)))
1676 newenv)))
1677 (macroexpand-all `(letrec ,(nreverse binds) ,@body)
1678 ;; Don't override lexical-let's macro-expander.
1679 (if (assq 'function newenv) newenv
1680 (cons (cons 'function #'cl--labels-convert) newenv)))))
1682 ;; The following ought to have a better definition for use with newer
1683 ;; byte compilers.
1684 ;;;###autoload
1685 (defmacro cl-macrolet (bindings &rest body)
1686 "Make temporary macro definitions.
1687 This is like `cl-flet', but for macros instead of functions.
1689 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
1690 (declare (indent 1)
1691 (debug
1692 ((&rest (&define name (&rest arg) cl-declarations-or-string
1693 def-body))
1694 cl-declarations body)))
1695 (if (cdr bindings)
1696 `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
1697 (if (null bindings) (cons 'progn body)
1698 (let* ((name (caar bindings))
1699 (res (cl--transform-lambda (cdar bindings) name)))
1700 (eval (car res))
1701 (macroexpand-all (cons 'progn body)
1702 (cons (cons name `(lambda ,@(cdr res)))
1703 macroexpand-all-environment))))))
1705 (defconst cl--old-macroexpand
1706 (if (and (boundp 'cl--old-macroexpand)
1707 (eq (symbol-function 'macroexpand)
1708 #'cl--sm-macroexpand))
1709 cl--old-macroexpand
1710 (symbol-function 'macroexpand)))
1712 (defun cl--sm-macroexpand (exp &optional env)
1713 "Special macro expander used inside `cl-symbol-macrolet'.
1714 This function replaces `macroexpand' during macro expansion
1715 of `cl-symbol-macrolet', and does the same thing as `macroexpand'
1716 except that it additionally expands symbol macros."
1717 (let ((macroexpand-all-environment env))
1718 (while
1719 (progn
1720 (setq exp (funcall cl--old-macroexpand exp env))
1721 (pcase exp
1722 ((pred symbolp)
1723 ;; Perform symbol-macro expansion.
1724 (when (cdr (assq (symbol-name exp) env))
1725 (setq exp (cadr (assq (symbol-name exp) env)))))
1726 (`(setq . ,_)
1727 ;; Convert setq to setf if required by symbol-macro expansion.
1728 (let* ((args (mapcar (lambda (f) (cl--sm-macroexpand f env))
1729 (cdr exp)))
1730 (p args))
1731 (while (and p (symbolp (car p))) (setq p (cddr p)))
1732 (if p (setq exp (cons 'setf args))
1733 (setq exp (cons 'setq args))
1734 ;; Don't loop further.
1735 nil)))
1736 (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
1737 ;; CL's symbol-macrolet treats re-bindings as candidates for
1738 ;; expansion (turning the let into a letf if needed), contrary to
1739 ;; Common-Lisp where such re-bindings hide the symbol-macro.
1740 (let ((letf nil) (found nil) (nbs ()))
1741 (dolist (binding bindings)
1742 (let* ((var (if (symbolp binding) binding (car binding)))
1743 (sm (assq (symbol-name var) env)))
1744 (push (if (not (cdr sm))
1745 binding
1746 (let ((nexp (cadr sm)))
1747 (setq found t)
1748 (unless (symbolp nexp) (setq letf t))
1749 (cons nexp (cdr-safe binding))))
1750 nbs)))
1751 (when found
1752 (setq exp `(,(if letf
1753 (if (eq (car exp) 'let) 'cl-letf 'cl-letf*)
1754 (car exp))
1755 ,(nreverse nbs)
1756 ,@body)))))
1757 ;; FIXME: The behavior of CL made sense in a dynamically scoped
1758 ;; language, but for lexical scoping, Common-Lisp's behavior might
1759 ;; make more sense (and indeed, CL behaves like Common-Lisp w.r.t
1760 ;; lexical-let), so maybe we should adjust the behavior based on
1761 ;; the use of lexical-binding.
1762 ;; (`(,(or `let `let*) . ,(or `(,bindings . ,body) dontcare))
1763 ;; (let ((nbs ()) (found nil))
1764 ;; (dolist (binding bindings)
1765 ;; (let* ((var (if (symbolp binding) binding (car binding)))
1766 ;; (name (symbol-name var))
1767 ;; (val (and found (consp binding) (eq 'let* (car exp))
1768 ;; (list (macroexpand-all (cadr binding)
1769 ;; env)))))
1770 ;; (push (if (assq name env)
1771 ;; ;; This binding should hide its symbol-macro,
1772 ;; ;; but given the way macroexpand-all works, we
1773 ;; ;; can't prevent application of `env' to the
1774 ;; ;; sub-expressions, so we need to α-rename this
1775 ;; ;; variable instead.
1776 ;; (let ((nvar (make-symbol
1777 ;; (copy-sequence name))))
1778 ;; (setq found t)
1779 ;; (push (list name nvar) env)
1780 ;; (cons nvar (or val (cdr-safe binding))))
1781 ;; (if val (cons var val) binding))
1782 ;; nbs)))
1783 ;; (when found
1784 ;; (setq exp `(,(car exp)
1785 ;; ,(nreverse nbs)
1786 ;; ,@(macroexp-unprogn
1787 ;; (macroexpand-all (macroexp-progn body)
1788 ;; env)))))
1789 ;; nil))
1791 exp))
1793 ;;;###autoload
1794 (defmacro cl-symbol-macrolet (bindings &rest body)
1795 "Make symbol macro definitions.
1796 Within the body FORMs, references to the variable NAME will be replaced
1797 by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...).
1799 \(fn ((NAME EXPANSION) ...) FORM...)"
1800 (declare (indent 1) (debug ((&rest (symbol sexp)) cl-declarations body)))
1801 (cond
1802 ((cdr bindings)
1803 `(cl-symbol-macrolet (,(car bindings))
1804 (cl-symbol-macrolet ,(cdr bindings) ,@body)))
1805 ((null bindings) (macroexp-progn body))
1807 (let ((previous-macroexpand (symbol-function 'macroexpand)))
1808 (unwind-protect
1809 (progn
1810 (fset 'macroexpand #'cl--sm-macroexpand)
1811 ;; FIXME: For N bindings, this will traverse `body' N times!
1812 (macroexpand-all (cons 'progn body)
1813 (cons (list (symbol-name (caar bindings))
1814 (cl-cadar bindings))
1815 macroexpand-all-environment)))
1816 (fset 'macroexpand previous-macroexpand))))))
1818 ;;; Multiple values.
1820 ;;;###autoload
1821 (defmacro cl-multiple-value-bind (vars form &rest body)
1822 "Collect multiple return values.
1823 FORM must return a list; the BODY is then executed with the first N elements
1824 of this list bound (`let'-style) to each of the symbols SYM in turn. This
1825 is analogous to the Common Lisp `cl-multiple-value-bind' macro, using lists to
1826 simulate true multiple return values. For compatibility, (cl-values A B C) is
1827 a synonym for (list A B C).
1829 \(fn (SYM...) FORM BODY)"
1830 (declare (indent 2) (debug ((&rest symbolp) form body)))
1831 (let ((temp (make-symbol "--cl-var--")) (n -1))
1832 `(let* ((,temp ,form)
1833 ,@(mapcar (lambda (v)
1834 (list v `(nth ,(setq n (1+ n)) ,temp)))
1835 vars))
1836 ,@body)))
1838 ;;;###autoload
1839 (defmacro cl-multiple-value-setq (vars form)
1840 "Collect multiple return values.
1841 FORM must return a list; the first N elements of this list are stored in
1842 each of the symbols SYM in turn. This is analogous to the Common Lisp
1843 `cl-multiple-value-setq' macro, using lists to simulate true multiple return
1844 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
1846 \(fn (SYM...) FORM)"
1847 (declare (indent 1) (debug ((&rest symbolp) form)))
1848 (cond ((null vars) `(progn ,form nil))
1849 ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
1851 (let* ((temp (make-symbol "--cl-var--")) (n 0))
1852 `(let ((,temp ,form))
1853 (prog1 (setq ,(pop vars) (car ,temp))
1854 (setq ,@(apply #'nconc
1855 (mapcar (lambda (v)
1856 (list v `(nth ,(setq n (1+ n))
1857 ,temp)))
1858 vars)))))))))
1861 ;;; Declarations.
1863 ;;;###autoload
1864 (defmacro cl-locally (&rest body)
1865 (declare (debug t))
1866 (cons 'progn body))
1867 ;;;###autoload
1868 (defmacro cl-the (_type form)
1869 (declare (indent 1) (debug (cl-type-spec form)))
1870 form)
1872 (defvar cl-proclaim-history t) ; for future compilers
1873 (defvar cl-declare-stack t) ; for future compilers
1875 (defun cl-do-proclaim (spec hist)
1876 (and hist (listp cl-proclaim-history) (push spec cl-proclaim-history))
1877 (cond ((eq (car-safe spec) 'special)
1878 (if (boundp 'byte-compile-bound-variables)
1879 (setq byte-compile-bound-variables
1880 (append (cdr spec) byte-compile-bound-variables))))
1882 ((eq (car-safe spec) 'inline)
1883 (while (setq spec (cdr spec))
1884 (or (memq (get (car spec) 'byte-optimizer)
1885 '(nil byte-compile-inline-expand))
1886 (error "%s already has a byte-optimizer, can't make it inline"
1887 (car spec)))
1888 (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
1890 ((eq (car-safe spec) 'notinline)
1891 (while (setq spec (cdr spec))
1892 (if (eq (get (car spec) 'byte-optimizer)
1893 'byte-compile-inline-expand)
1894 (put (car spec) 'byte-optimizer nil))))
1896 ((eq (car-safe spec) 'optimize)
1897 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
1898 '((0 nil) (1 t) (2 t) (3 t))))
1899 (safety (assq (nth 1 (assq 'safety (cdr spec)))
1900 '((0 t) (1 t) (2 t) (3 nil)))))
1901 (if speed (setq cl-optimize-speed (car speed)
1902 byte-optimize (nth 1 speed)))
1903 (if safety (setq cl-optimize-safety (car safety)
1904 byte-compile-delete-errors (nth 1 safety)))))
1906 ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
1907 (while (setq spec (cdr spec))
1908 (if (consp (car spec))
1909 (if (eq (cl-cadar spec) 0)
1910 (byte-compile-disable-warning (caar spec))
1911 (byte-compile-enable-warning (caar spec)))))))
1912 nil)
1914 ;;; Process any proclamations made before cl-macs was loaded.
1915 (defvar cl-proclaims-deferred)
1916 (let ((p (reverse cl-proclaims-deferred)))
1917 (while p (cl-do-proclaim (pop p) t))
1918 (setq cl-proclaims-deferred nil))
1920 ;;;###autoload
1921 (defmacro cl-declare (&rest specs)
1922 "Declare SPECS about the current function while compiling.
1923 For instance
1925 \(cl-declare (warn 0))
1927 will turn off byte-compile warnings in the function.
1928 See Info node `(cl)Declarations' for details."
1929 (if (cl--compiling-file)
1930 (while specs
1931 (if (listp cl-declare-stack) (push (car specs) cl-declare-stack))
1932 (cl-do-proclaim (pop specs) nil)))
1933 nil)
1935 ;;; The standard modify macros.
1937 ;; `setf' is now part of core Elisp, defined in gv.el.
1939 ;;;###autoload
1940 (defmacro cl-psetf (&rest args)
1941 "Set PLACEs to the values VALs in parallel.
1942 This is like `setf', except that all VAL forms are evaluated (in order)
1943 before assigning any PLACEs to the corresponding values.
1945 \(fn PLACE VAL PLACE VAL ...)"
1946 (declare (debug setf))
1947 (let ((p args) (simple t) (vars nil))
1948 (while p
1949 (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
1950 (setq simple nil))
1951 (if (memq (car p) vars)
1952 (error "Destination duplicated in psetf: %s" (car p)))
1953 (push (pop p) vars)
1954 (or p (error "Odd number of arguments to cl-psetf"))
1955 (pop p))
1956 (if simple
1957 `(progn (setq ,@args) nil)
1958 (setq args (reverse args))
1959 (let ((expr `(setf ,(cadr args) ,(car args))))
1960 (while (setq args (cddr args))
1961 (setq expr `(setf ,(cadr args) (prog1 ,(car args) ,expr))))
1962 `(progn ,expr nil)))))
1964 ;;;###autoload
1965 (defmacro cl-remf (place tag)
1966 "Remove TAG from property list PLACE.
1967 PLACE may be a symbol, or any generalized variable allowed by `setf'.
1968 The form returns true if TAG was found and removed, nil otherwise."
1969 (declare (debug (place form)))
1970 (gv-letplace (tval setter) place
1971 (macroexp-let2 macroexp-copyable-p ttag tag
1972 `(if (eq ,ttag (car ,tval))
1973 (progn ,(funcall setter `(cddr ,tval))
1975 (cl--do-remf ,tval ,ttag)))))
1977 ;;;###autoload
1978 (defmacro cl-shiftf (place &rest args)
1979 "Shift left among PLACEs.
1980 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
1981 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
1983 \(fn PLACE... VAL)"
1984 (declare (debug (&rest place)))
1985 (cond
1986 ((null args) place)
1987 ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
1989 (gv-letplace (getter setter) place
1990 `(prog1 ,getter
1991 ,(funcall setter `(cl-shiftf ,@args)))))))
1993 ;;;###autoload
1994 (defmacro cl-rotatef (&rest args)
1995 "Rotate left among PLACEs.
1996 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
1997 Each PLACE may be a symbol, or any generalized variable allowed by `setf'.
1999 \(fn PLACE...)"
2000 (declare (debug (&rest place)))
2001 (if (not (memq nil (mapcar 'symbolp args)))
2002 (and (cdr args)
2003 (let ((sets nil)
2004 (first (car args)))
2005 (while (cdr args)
2006 (setq sets (nconc sets (list (pop args) (car args)))))
2007 `(cl-psetf ,@sets ,(car args) ,first)))
2008 (let* ((places (reverse args))
2009 (temp (make-symbol "--cl-rotatef--"))
2010 (form temp))
2011 (while (cdr places)
2012 (setq form
2013 (gv-letplace (getter setter) (pop places)
2014 `(prog1 ,getter ,(funcall setter form)))))
2015 (gv-letplace (getter setter) (car places)
2016 (macroexp-let* `((,temp ,getter))
2017 `(progn ,(funcall setter form) nil))))))
2019 ;; FIXME: `letf' is unsatisfactory because it does not really "restore" the
2020 ;; previous state. If the getter/setter loses information, that info is
2021 ;; not recovered.
2023 (defun cl--letf (bindings simplebinds binds body)
2024 ;; It's not quite clear what the semantics of cl-letf should be.
2025 ;; E.g. in (cl-letf ((PLACE1 VAL1) (PLACE2 VAL2)) BODY), while it's clear
2026 ;; that the actual assignments ("bindings") should only happen after
2027 ;; evaluating VAL1 and VAL2, it's not clear when the sub-expressions of
2028 ;; PLACE1 and PLACE2 should be evaluated. Should we have
2029 ;; PLACE1; VAL1; PLACE2; VAL2; bind1; bind2
2030 ;; or
2031 ;; VAL1; VAL2; PLACE1; PLACE2; bind1; bind2
2032 ;; or
2033 ;; VAL1; VAL2; PLACE1; bind1; PLACE2; bind2
2034 ;; Common-Lisp's `psetf' does the first, so we'll do the same.
2035 (if (null bindings)
2036 (if (and (null binds) (null simplebinds)) (macroexp-progn body)
2037 `(let* (,@(mapcar (lambda (x)
2038 (pcase-let ((`(,vold ,getter ,_setter ,_vnew) x))
2039 (list vold getter)))
2040 binds)
2041 ,@simplebinds)
2042 (unwind-protect
2043 ,(macroexp-progn
2044 (append
2045 (delq nil
2046 (mapcar (lambda (x)
2047 (pcase x
2048 ;; If there's no vnew, do nothing.
2049 (`(,_vold ,_getter ,setter ,vnew)
2050 (funcall setter vnew))))
2051 binds))
2052 body))
2053 ,@(mapcar (lambda (x)
2054 (pcase-let ((`(,vold ,_getter ,setter ,_vnew) x))
2055 (funcall setter vold)))
2056 binds))))
2057 (let ((binding (car bindings)))
2058 (gv-letplace (getter setter) (car binding)
2059 (macroexp-let2 nil vnew (cadr binding)
2060 (if (symbolp (car binding))
2061 ;; Special-case for simple variables.
2062 (cl--letf (cdr bindings)
2063 (cons `(,getter ,(if (cdr binding) vnew getter))
2064 simplebinds)
2065 binds body)
2066 (cl--letf (cdr bindings) simplebinds
2067 (cons `(,(make-symbol "old") ,getter ,setter
2068 ,@(if (cdr binding) (list vnew)))
2069 binds)
2070 body)))))))
2072 ;;;###autoload
2073 (defmacro cl-letf (bindings &rest body)
2074 "Temporarily bind to PLACEs.
2075 This is the analogue of `let', but with generalized variables (in the
2076 sense of `setf') for the PLACEs. Each PLACE is set to the corresponding
2077 VALUE, then the BODY forms are executed. On exit, either normally or
2078 because of a `throw' or error, the PLACEs are set back to their original
2079 values. Note that this macro is *not* available in Common Lisp.
2080 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2081 the PLACE is not modified before executing BODY.
2083 \(fn ((PLACE VALUE) ...) BODY...)"
2084 (declare (indent 1) (debug ((&rest (gate gv-place &optional form)) body)))
2085 (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2086 `(let ,bindings ,@body)
2087 (cl--letf bindings () () body)))
2089 ;;;###autoload
2090 (defmacro cl-letf* (bindings &rest body)
2091 "Temporarily bind to PLACEs.
2092 Like `cl-letf' but where the bindings are performed one at a time,
2093 rather than all at the end (i.e. like `let*' rather than like `let')."
2094 (declare (indent 1) (debug cl-letf))
2095 (dolist (binding (reverse bindings))
2096 (setq body (list `(cl-letf (,binding) ,@body))))
2097 (macroexp-progn body))
2099 ;;;###autoload
2100 (defmacro cl-callf (func place &rest args)
2101 "Set PLACE to (FUNC PLACE ARGS...).
2102 FUNC should be an unquoted function name. PLACE may be a symbol,
2103 or any generalized variable allowed by `setf'."
2104 (declare (indent 2) (debug (cl-function place &rest form)))
2105 (gv-letplace (getter setter) place
2106 (let* ((rargs (cons getter args)))
2107 (funcall setter
2108 (if (symbolp func) (cons func rargs)
2109 `(funcall #',func ,@rargs))))))
2111 ;;;###autoload
2112 (defmacro cl-callf2 (func arg1 place &rest args)
2113 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2114 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2116 \(fn FUNC ARG1 PLACE ARGS...)"
2117 (declare (indent 3) (debug (cl-function form place &rest form)))
2118 (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
2119 `(setf ,place (,func ,arg1 ,place ,@args))
2120 (macroexp-let2 nil a1 arg1
2121 (gv-letplace (getter setter) place
2122 (let* ((rargs (cl-list* a1 getter args)))
2123 (funcall setter
2124 (if (symbolp func) (cons func rargs)
2125 `(funcall #',func ,@rargs))))))))
2127 ;;; Structures.
2129 ;;;###autoload
2130 (defmacro cl-defstruct (struct &rest descs)
2131 "Define a struct type.
2132 This macro defines a new data type called NAME that stores data
2133 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2134 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2135 You can use the accessors to set the corresponding slots, via `setf'.
2137 NAME may instead take the form (NAME OPTIONS...), where each
2138 OPTION is either a single keyword or (KEYWORD VALUE).
2139 See Info node `(cl)Structures' for a list of valid keywords.
2141 Each SLOT may instead take the form (SLOT SLOT-OPTS...), where
2142 SLOT-OPTS are keyword-value pairs for that slot. Currently, only
2143 one keyword is supported, `:read-only'. If this has a non-nil
2144 value, that slot cannot be set via `setf'.
2146 \(fn NAME SLOTS...)"
2147 (declare (doc-string 2) (indent 1)
2148 (debug
2149 (&define ;Makes top-level form not be wrapped.
2150 [&or symbolp
2151 (gate
2152 symbolp &rest
2153 (&or [":conc-name" symbolp]
2154 [":constructor" symbolp &optional cl-lambda-list]
2155 [":copier" symbolp]
2156 [":predicate" symbolp]
2157 [":include" symbolp &rest sexp] ;; Not finished.
2158 ;; The following are not supported.
2159 ;; [":print-function" ...]
2160 ;; [":type" ...]
2161 ;; [":initial-offset" ...]
2163 [&optional stringp]
2164 ;; All the above is for the following def-form.
2165 &rest &or symbolp (symbolp def-form
2166 &optional ":read-only" sexp))))
2167 (let* ((name (if (consp struct) (car struct) struct))
2168 (opts (cdr-safe struct))
2169 (slots nil)
2170 (defaults nil)
2171 (conc-name (concat (symbol-name name) "-"))
2172 (constructor (intern (format "make-%s" name)))
2173 (constrs nil)
2174 (copier (intern (format "copy-%s" name)))
2175 (predicate (intern (format "%s-p" name)))
2176 (print-func nil) (print-auto nil)
2177 (safety (if (cl--compiling-file) cl-optimize-safety 3))
2178 (include nil)
2179 (tag (intern (format "cl-struct-%s" name)))
2180 (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2181 (include-descs nil)
2182 (side-eff nil)
2183 (type nil)
2184 (named nil)
2185 (forms nil)
2186 pred-form pred-check)
2187 (if (stringp (car descs))
2188 (push `(put ',name 'structure-documentation
2189 ,(pop descs)) forms))
2190 (setq descs (cons '(cl-tag-slot)
2191 (mapcar (function (lambda (x) (if (consp x) x (list x))))
2192 descs)))
2193 (while opts
2194 (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2195 (args (cdr-safe (pop opts))))
2196 (cond ((eq opt :conc-name)
2197 (if args
2198 (setq conc-name (if (car args)
2199 (symbol-name (car args)) ""))))
2200 ((eq opt :constructor)
2201 (if (cdr args)
2202 (progn
2203 ;; If this defines a constructor of the same name as
2204 ;; the default one, don't define the default.
2205 (if (eq (car args) constructor)
2206 (setq constructor nil))
2207 (push args constrs))
2208 (if args (setq constructor (car args)))))
2209 ((eq opt :copier)
2210 (if args (setq copier (car args))))
2211 ((eq opt :predicate)
2212 (if args (setq predicate (car args))))
2213 ((eq opt :include)
2214 (setq include (car args)
2215 include-descs (mapcar (function
2216 (lambda (x)
2217 (if (consp x) x (list x))))
2218 (cdr args))))
2219 ((eq opt :print-function)
2220 (setq print-func (car args)))
2221 ((eq opt :type)
2222 (setq type (car args)))
2223 ((eq opt :named)
2224 (setq named t))
2225 ((eq opt :initial-offset)
2226 (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2227 descs)))
2229 (error "Slot option %s unrecognized" opt)))))
2230 (if print-func
2231 (setq print-func
2232 `(progn (funcall #',print-func cl-x cl-s cl-n) t))
2233 (or type (and include (not (get include 'cl-struct-print)))
2234 (setq print-auto t
2235 print-func (and (or (not (or include type)) (null print-func))
2236 `(progn
2237 (princ ,(format "#S(%s" name) cl-s))))))
2238 (if include
2239 (let ((inc-type (get include 'cl-struct-type))
2240 (old-descs (get include 'cl-struct-slots)))
2241 (or inc-type (error "%s is not a struct name" include))
2242 (and type (not (eq (car inc-type) type))
2243 (error ":type disagrees with :include for %s" name))
2244 (while include-descs
2245 (setcar (memq (or (assq (caar include-descs) old-descs)
2246 (error "No slot %s in included struct %s"
2247 (caar include-descs) include))
2248 old-descs)
2249 (pop include-descs)))
2250 (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2251 type (car inc-type)
2252 named (assq 'cl-tag-slot descs))
2253 (if (cadr inc-type) (setq tag name named t))
2254 (let ((incl include))
2255 (while incl
2256 (push `(cl-pushnew ',tag
2257 ,(intern (format "cl-struct-%s-tags" incl)))
2258 forms)
2259 (setq incl (get incl 'cl-struct-include)))))
2260 (if type
2261 (progn
2262 (or (memq type '(vector list))
2263 (error "Invalid :type specifier: %s" type))
2264 (if named (setq tag name)))
2265 (setq type 'vector named 'true)))
2266 (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2267 (push `(defvar ,tag-symbol) forms)
2268 (setq pred-form (and named
2269 (let ((pos (- (length descs)
2270 (length (memq (assq 'cl-tag-slot descs)
2271 descs)))))
2272 (if (eq type 'vector)
2273 `(and (vectorp cl-x)
2274 (>= (length cl-x) ,(length descs))
2275 (memq (aref cl-x ,pos) ,tag-symbol))
2276 (if (= pos 0)
2277 `(memq (car-safe cl-x) ,tag-symbol)
2278 `(and (consp cl-x)
2279 (memq (nth ,pos cl-x) ,tag-symbol))))))
2280 pred-check (and pred-form (> safety 0)
2281 (if (and (eq (cl-caadr pred-form) 'vectorp)
2282 (= safety 1))
2283 (cons 'and (cl-cdddr pred-form)) pred-form)))
2284 (let ((pos 0) (descp descs))
2285 (while descp
2286 (let* ((desc (pop descp))
2287 (slot (car desc)))
2288 (if (memq slot '(cl-tag-slot cl-skip-slot))
2289 (progn
2290 (push nil slots)
2291 (push (and (eq slot 'cl-tag-slot) `',tag)
2292 defaults))
2293 (if (assq slot descp)
2294 (error "Duplicate slots named %s in %s" slot name))
2295 (let ((accessor (intern (format "%s%s" conc-name slot))))
2296 (push slot slots)
2297 (push (nth 1 desc) defaults)
2298 (push `(cl-defsubst ,accessor (cl-x)
2299 ,@(and pred-check
2300 (list `(or ,pred-check
2301 (error "%s accessing a non-%s"
2302 ',accessor ',name))))
2303 ,(if (eq type 'vector) `(aref cl-x ,pos)
2304 (if (= pos 0) '(car cl-x)
2305 `(nth ,pos cl-x)))) forms)
2306 (push (cons accessor t) side-eff)
2307 ;; Don't bother defining a setf-expander, since gv-get can use
2308 ;; the compiler macro to get the same result.
2309 ;;(push `(gv-define-setter ,accessor (cl-val cl-x)
2310 ;; ,(if (cadr (memq :read-only (cddr desc)))
2311 ;; `(progn (ignore cl-x cl-val)
2312 ;; (error "%s is a read-only slot"
2313 ;; ',accessor))
2314 ;; ;; If cl is loaded only for compilation,
2315 ;; ;; the call to cl--struct-setf-expander would
2316 ;; ;; cause a warning because it may not be
2317 ;; ;; defined at run time. Suppress that warning.
2318 ;; `(progn
2319 ;; (declare-function
2320 ;; cl--struct-setf-expander "cl-macs"
2321 ;; (x name accessor pred-form pos))
2322 ;; (cl--struct-setf-expander
2323 ;; cl-val cl-x ',name ',accessor
2324 ;; ,(and pred-check `',pred-check)
2325 ;; ,pos))))
2326 ;; forms)
2327 (if print-auto
2328 (nconc print-func
2329 (list `(princ ,(format " %s" slot) cl-s)
2330 `(prin1 (,accessor cl-x) cl-s)))))))
2331 (setq pos (1+ pos))))
2332 (setq slots (nreverse slots)
2333 defaults (nreverse defaults))
2334 (and predicate pred-form
2335 (progn (push `(cl-defsubst ,predicate (cl-x)
2336 ,(if (eq (car pred-form) 'and)
2337 (append pred-form '(t))
2338 `(and ,pred-form t))) forms)
2339 (push (cons predicate 'error-free) side-eff)))
2340 (and copier
2341 (progn (push `(defun ,copier (x) (copy-sequence x)) forms)
2342 (push (cons copier t) side-eff)))
2343 (if constructor
2344 (push (list constructor
2345 (cons '&key (delq nil (copy-sequence slots))))
2346 constrs))
2347 (while constrs
2348 (let* ((name (caar constrs))
2349 (args (cadr (pop constrs)))
2350 (anames (cl--arglist-args args))
2351 (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
2352 slots defaults)))
2353 (push `(cl-defsubst ,name
2354 (&cl-defs '(nil ,@descs) ,@args)
2355 (,type ,@make)) forms)
2356 (if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
2357 (push (cons name t) side-eff))))
2358 (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2359 ;; Don't bother adding to cl-custom-print-functions since it's not used
2360 ;; by anything anyway!
2361 ;;(if print-func
2362 ;; (push `(if (boundp 'cl-custom-print-functions)
2363 ;; (push
2364 ;; ;; The auto-generated function does not pay attention to
2365 ;; ;; the depth argument cl-n.
2366 ;; (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2367 ;; (and ,pred-form ,print-func))
2368 ;; cl-custom-print-functions))
2369 ;; forms))
2370 (push `(setq ,tag-symbol (list ',tag)) forms)
2371 (push `(cl-eval-when (compile load eval)
2372 (put ',name 'cl-struct-slots ',descs)
2373 (put ',name 'cl-struct-type ',(list type (eq named t)))
2374 (put ',name 'cl-struct-include ',include)
2375 (put ',name 'cl-struct-print ,print-auto)
2376 ,@(mapcar (lambda (x)
2377 `(put ',(car x) 'side-effect-free ',(cdr x)))
2378 side-eff))
2379 forms)
2380 `(progn ,@(nreverse (cons `',name forms)))))
2382 ;;; Types and assertions.
2384 ;;;###autoload
2385 (defmacro cl-deftype (name arglist &rest body)
2386 "Define NAME as a new data type.
2387 The type name can then be used in `cl-typecase', `cl-check-type', etc."
2388 (declare (debug cl-defmacro) (doc-string 3))
2389 `(cl-eval-when (compile load eval)
2390 (put ',name 'cl-deftype-handler
2391 (cl-function (lambda (&cl-defs '('*) ,@arglist) ,@body)))))
2393 (defun cl--make-type-test (val type)
2394 (if (symbolp type)
2395 (cond ((get type 'cl-deftype-handler)
2396 (cl--make-type-test val (funcall (get type 'cl-deftype-handler))))
2397 ((memq type '(nil t)) type)
2398 ((eq type 'null) `(null ,val))
2399 ((eq type 'atom) `(atom ,val))
2400 ((eq type 'float) `(cl-floatp-safe ,val))
2401 ((eq type 'real) `(numberp ,val))
2402 ((eq type 'fixnum) `(integerp ,val))
2403 ;; FIXME: Should `character' accept things like ?\C-\M-a ? --Stef
2404 ((memq type '(character string-char)) `(characterp ,val))
2406 (let* ((name (symbol-name type))
2407 (namep (intern (concat name "p"))))
2408 (if (fboundp namep) (list namep val)
2409 (list (intern (concat name "-p")) val)))))
2410 (cond ((get (car type) 'cl-deftype-handler)
2411 (cl--make-type-test val (apply (get (car type) 'cl-deftype-handler)
2412 (cdr type))))
2413 ((memq (car type) '(integer float real number))
2414 (delq t `(and ,(cl--make-type-test val (car type))
2415 ,(if (memq (cadr type) '(* nil)) t
2416 (if (consp (cadr type)) `(> ,val ,(cl-caadr type))
2417 `(>= ,val ,(cadr type))))
2418 ,(if (memq (cl-caddr type) '(* nil)) t
2419 (if (consp (cl-caddr type)) `(< ,val ,(cl-caaddr type))
2420 `(<= ,val ,(cl-caddr type)))))))
2421 ((memq (car type) '(and or not))
2422 (cons (car type)
2423 (mapcar (function (lambda (x) (cl--make-type-test val x)))
2424 (cdr type))))
2425 ((memq (car type) '(member cl-member))
2426 `(and (cl-member ,val ',(cdr type)) t))
2427 ((eq (car type) 'satisfies) (list (cadr type) val))
2428 (t (error "Bad type spec: %s" type)))))
2430 (defvar cl--object)
2431 ;;;###autoload
2432 (defun cl-typep (object type) ; See compiler macro below.
2433 "Check that OBJECT is of type TYPE.
2434 TYPE is a Common Lisp-style type specifier."
2435 (let ((cl--object object)) ;; Yuck!!
2436 (eval (cl--make-type-test 'cl--object type))))
2438 ;;;###autoload
2439 (defmacro cl-check-type (form type &optional string)
2440 "Verify that FORM is of type TYPE; signal an error if not.
2441 STRING is an optional description of the desired type."
2442 (declare (debug (place cl-type-spec &optional stringp)))
2443 (and (or (not (cl--compiling-file))
2444 (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2445 (let* ((temp (if (cl--simple-expr-p form 3)
2446 form (make-symbol "--cl-var--")))
2447 (body `(or ,(cl--make-type-test temp type)
2448 (signal 'wrong-type-argument
2449 (list ,(or string `',type)
2450 ,temp ',form)))))
2451 (if (eq temp form) `(progn ,body nil)
2452 `(let ((,temp ,form)) ,body nil)))))
2454 ;;;###autoload
2455 (defmacro cl-assert (form &optional show-args string &rest args)
2456 ;; FIXME: This is actually not compatible with Common-Lisp's `assert'.
2457 "Verify that FORM returns non-nil; signal an error if not.
2458 Second arg SHOW-ARGS means to include arguments of FORM in message.
2459 Other args STRING and ARGS... are arguments to be passed to `error'.
2460 They are not evaluated unless the assertion fails. If STRING is
2461 omitted, a default message listing FORM itself is used."
2462 (declare (debug (form &rest form)))
2463 (and (or (not (cl--compiling-file))
2464 (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2465 (let ((sargs (and show-args
2466 (delq nil (mapcar (lambda (x)
2467 (unless (macroexp-const-p x)
2469 (cdr form))))))
2470 `(progn
2471 (or ,form
2472 ,(if string
2473 `(error ,string ,@sargs ,@args)
2474 `(signal 'cl-assertion-failed
2475 (list ',form ,@sargs))))
2476 nil))))
2478 ;;; Compiler macros.
2480 ;;;###autoload
2481 (defmacro cl-define-compiler-macro (func args &rest body)
2482 "Define a compiler-only macro.
2483 This is like `defmacro', but macro expansion occurs only if the call to
2484 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
2485 for optimizing the way calls to FUNC are compiled; the form returned by
2486 BODY should do the same thing as a call to the normal function called
2487 FUNC, though possibly more efficiently. Note that, like regular macros,
2488 compiler macros are expanded repeatedly until no further expansions are
2489 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
2490 original function call alone by declaring an initial `&whole foo' parameter
2491 and then returning foo."
2492 (declare (debug cl-defmacro))
2493 (let ((p args) (res nil))
2494 (while (consp p) (push (pop p) res))
2495 (setq args (nconc (nreverse res) (and p (list '&rest p)))))
2496 `(cl-eval-when (compile load eval)
2497 (put ',func 'compiler-macro
2498 (cl-function (lambda ,(if (memq '&whole args) (delq '&whole args)
2499 (cons '_cl-whole-arg args))
2500 ,@body)))
2501 ;; This is so that describe-function can locate
2502 ;; the macro definition.
2503 (let ((file ,(or buffer-file-name
2504 (and (boundp 'byte-compile-current-file)
2505 (stringp byte-compile-current-file)
2506 byte-compile-current-file))))
2507 (if file (put ',func 'compiler-macro-file
2508 (purecopy (file-name-nondirectory file)))))))
2510 ;;;###autoload
2511 (defun cl-compiler-macroexpand (form)
2512 (while
2513 (let ((func (car-safe form)) (handler nil))
2514 (while (and (symbolp func)
2515 (not (setq handler (get func 'compiler-macro)))
2516 (fboundp func)
2517 (or (not (autoloadp (symbol-function func)))
2518 (autoload-do-load (symbol-function func) func)))
2519 (setq func (symbol-function func)))
2520 (and handler
2521 (not (eq form (setq form (apply handler form (cdr form))))))))
2522 form)
2524 ;; Optimize away unused block-wrappers.
2526 (defvar cl--active-block-names nil)
2528 (cl-define-compiler-macro cl--block-wrapper (cl-form)
2529 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
2530 (cl--active-block-names (cons cl-entry cl--active-block-names))
2531 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
2532 (cons 'progn (cddr cl-form))
2533 macroexpand-all-environment)))
2534 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
2535 ;; to indicate that this return value is already fully expanded.
2536 (if (cdr cl-entry)
2537 `(catch ,(nth 1 cl-form) ,@(cdr cl-body))
2538 cl-body)))
2540 (cl-define-compiler-macro cl--block-throw (cl-tag cl-value)
2541 (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
2542 (if cl-found (setcdr cl-found t)))
2543 `(throw ,cl-tag ,cl-value))
2545 ;;;###autoload
2546 (defmacro cl-defsubst (name args &rest body)
2547 "Define NAME as a function.
2548 Like `defun', except the function is automatically declared `inline',
2549 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2550 surrounded by (cl-block NAME ...).
2552 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2553 (declare (debug cl-defun) (indent 2))
2554 (let* ((argns (cl--arglist-args args)) (p argns)
2555 (pbody (cons 'progn body))
2556 (unsafe (not (cl--safe-expr-p pbody))))
2557 (while (and p (eq (cl--expr-contains args (car p)) 1)) (pop p))
2558 `(progn
2559 ,(if p nil ; give up if defaults refer to earlier args
2560 `(cl-define-compiler-macro ,name
2561 ,(if (memq '&key args)
2562 `(&whole cl-whole &cl-quote ,@args)
2563 (cons '&cl-quote args))
2564 (cl--defsubst-expand
2565 ',argns '(cl-block ,name ,@body)
2566 ;; We used to pass `simple' as
2567 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2568 ;; But this is much too simplistic since it
2569 ;; does not pay attention to the argvs (and
2570 ;; cl-expr-access-order itself is also too naive).
2572 ,(and (memq '&key args) 'cl-whole) ,unsafe ,@argns)))
2573 (cl-defun ,name ,args ,@body))))
2575 (defun cl--defsubst-expand (argns body simple whole unsafe &rest argvs)
2576 (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
2577 (if (cl--simple-exprs-p argvs) (setq simple t))
2578 (let* ((substs ())
2579 (lets (delq nil
2580 (cl-mapcar (lambda (argn argv)
2581 (if (or simple (macroexp-const-p argv))
2582 (progn (push (cons argn argv) substs)
2583 (and unsafe (list argn argv)))
2584 (list argn argv)))
2585 argns argvs))))
2586 ;; FIXME: `sublis/subst' will happily substitute the symbol
2587 ;; `argn' in places where it's not used as a reference
2588 ;; to a variable.
2589 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
2590 ;; scope, leading to name capture.
2591 (setq body (cond ((null substs) body)
2592 ((null (cdr substs))
2593 (cl-subst (cdar substs) (caar substs) body))
2594 (t (cl-sublis substs body))))
2595 (if lets `(let ,lets ,body) body))))
2598 ;; Compile-time optimizations for some functions defined in this package.
2600 (defun cl--compiler-macro-member (form a list &rest keys)
2601 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
2602 (cl--const-expr-val (nth 1 keys)))))
2603 (cond ((eq test 'eq) `(memq ,a ,list))
2604 ((eq test 'equal) `(member ,a ,list))
2605 ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
2606 (t form))))
2608 (defun cl--compiler-macro-assoc (form a list &rest keys)
2609 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
2610 (cl--const-expr-val (nth 1 keys)))))
2611 (cond ((eq test 'eq) `(assq ,a ,list))
2612 ((eq test 'equal) `(assoc ,a ,list))
2613 ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
2614 (if (cl-floatp-safe (cl--const-expr-val a))
2615 `(assoc ,a ,list) `(assq ,a ,list)))
2616 (t form))))
2618 ;;;###autoload
2619 (defun cl--compiler-macro-adjoin (form a list &rest keys)
2620 (if (and (cl--simple-expr-p a) (cl--simple-expr-p list)
2621 (not (memq :key keys)))
2622 `(if (cl-member ,a ,list ,@keys) ,list (cons ,a ,list))
2623 form))
2625 (defun cl--compiler-macro-get (_form sym prop &optional def)
2626 (if def
2627 `(cl-getf (symbol-plist ,sym) ,prop ,def)
2628 `(get ,sym ,prop)))
2630 (cl-define-compiler-macro cl-typep (&whole form val type)
2631 (if (macroexp-const-p type)
2632 (macroexp-let2 macroexp-copyable-p temp val
2633 (cl--make-type-test temp (cl--const-expr-val type)))
2634 form))
2636 (dolist (y '(cl-first cl-second cl-third cl-fourth
2637 cl-fifth cl-sixth cl-seventh
2638 cl-eighth cl-ninth cl-tenth
2639 cl-rest cl-endp cl-plusp cl-minusp
2640 cl-caaar cl-caadr cl-cadar
2641 cl-caddr cl-cdaar cl-cdadr
2642 cl-cddar cl-cdddr cl-caaaar
2643 cl-caaadr cl-caadar cl-caaddr
2644 cl-cadaar cl-cadadr cl-caddar
2645 cl-cadddr cl-cdaaar cl-cdaadr
2646 cl-cdadar cl-cdaddr cl-cddaar
2647 cl-cddadr cl-cdddar cl-cddddr))
2648 (put y 'side-effect-free t))
2650 ;;; Things that are inline.
2651 (cl-proclaim '(inline cl-floatp-safe cl-acons cl-map cl-concatenate cl-notany
2652 cl-notevery cl--set-elt cl-revappend cl-nreconc gethash))
2654 ;;; Things that are side-effect-free.
2655 (mapc (lambda (x) (put x 'side-effect-free t))
2656 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd cl-lcm
2657 cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem cl-subseq
2658 cl-list-length cl-get cl-getf))
2660 ;;; Things that are side-effect-and-error-free.
2661 (mapc (lambda (x) (put x 'side-effect-free 'error-free))
2662 '(eql cl-floatp-safe cl-list* cl-subst cl-acons cl-equalp cl-random-state-p
2663 copy-tree cl-sublis))
2666 (run-hooks 'cl-macs-load-hook)
2668 ;; Local variables:
2669 ;; byte-compile-dynamic: t
2670 ;; byte-compile-warnings: (not cl-functions)
2671 ;; generated-autoload-file: "cl-loaddefs.el"
2672 ;; End:
2674 (provide 'cl-macs)
2676 ;;; cl-macs.el ends here