Cleanup cl-macs namespace. Add macro helpers in macroexp.el.
[emacs.git] / lisp / emacs-lisp / cl-macs.el
blobacb60373b5a11bd82430a5035f7e57e0e1c6f20e
1 ;;; cl-macs.el --- Common Lisp macros
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)
49 (defmacro cl-pop2 (place)
50 (declare (debug edebug-sexps))
51 `(prog1 (car (cdr ,place))
52 (setq ,place (cdr (cdr ,place)))))
54 (defvar cl-optimize-safety)
55 (defvar cl-optimize-speed)
58 ;; This kludge allows macros which use cl--transform-function-property
59 ;; to be called at compile-time.
61 (eval-and-compile
62 (or (fboundp 'cl--transform-function-property)
63 (defun cl--transform-function-property (n p f)
64 `(put ',n ',p #'(lambda . ,f)))))
66 ;;; Initialization.
68 ;;; Some predicates for analyzing Lisp forms.
69 ;; These are used by various
70 ;; macro expanders to optimize the results in certain common cases.
72 (defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
73 car-safe cdr-safe progn prog1 prog2))
74 (defconst cl--safe-funcs '(* / % length memq list vector vectorp
75 < > <= >= = error))
77 (defun cl--simple-expr-p (x &optional size)
78 "Check if no side effects, and executes quickly."
79 (or size (setq size 10))
80 (if (and (consp x) (not (memq (car x) '(quote function cl-function))))
81 (and (symbolp (car x))
82 (or (memq (car x) cl--simple-funcs)
83 (get (car x) 'side-effect-free))
84 (progn
85 (setq size (1- size))
86 (while (and (setq x (cdr x))
87 (setq size (cl--simple-expr-p (car x) size))))
88 (and (null x) (>= size 0) size)))
89 (and (> size 0) (1- size))))
91 (defun cl--simple-exprs-p (xs)
92 (while (and xs (cl--simple-expr-p (car xs)))
93 (setq xs (cdr xs)))
94 (not xs))
96 (defun cl--safe-expr-p (x)
97 "Check if no side effects."
98 (or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
99 (and (symbolp (car x))
100 (or (memq (car x) cl--simple-funcs)
101 (memq (car x) cl--safe-funcs)
102 (get (car x) 'side-effect-free))
103 (progn
104 (while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
105 (null x)))))
107 ;;; Check if constant (i.e., no side effects or dependencies).
108 (defun cl--const-expr-p (x)
109 (cond ((consp x)
110 (or (eq (car x) 'quote)
111 (and (memq (car x) '(function cl-function))
112 (or (symbolp (nth 1 x))
113 (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
114 ((symbolp x) (and (memq x '(nil t)) t))
115 (t t)))
117 (defun cl--const-expr-val (x)
118 (and (macroexp-const-p x) (if (consp x) (nth 1 x) x)))
120 (defun cl-expr-access-order (x v)
121 ;; This apparently tries to return nil iff the expression X evaluates
122 ;; the variables V in the same order as they appear in V (so as to
123 ;; be able to replace those vars with the expressions they're bound
124 ;; to).
125 ;; FIXME: This is very naive, it doesn't even check to see if those
126 ;; variables appear more than once.
127 (if (macroexp-const-p x) v
128 (if (consp x)
129 (progn
130 (while (setq x (cdr x)) (setq v (cl-expr-access-order (car x) v)))
132 (if (eq x (car v)) (cdr v) '(t)))))
134 (defun cl--expr-contains (x y)
135 "Count number of times X refers to Y. Return nil for 0 times."
136 ;; FIXME: This is naive, and it will cl-count Y as referred twice in
137 ;; (let ((Y 1)) Y) even though it should be 0. Also it is often called on
138 ;; non-macroexpanded code, so it may also miss some occurrences that would
139 ;; only appear in the expanded code.
140 (cond ((equal y x) 1)
141 ((and (consp x) (not (memq (car x) '(quote function cl-function))))
142 (let ((sum 0))
143 (while (consp x)
144 (setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
145 (setq sum (+ sum (or (cl--expr-contains x y) 0)))
146 (and (> sum 0) sum)))
147 (t nil)))
149 (defun cl--expr-contains-any (x y)
150 (while (and y (not (cl--expr-contains x (car y)))) (pop y))
153 (defun cl--expr-depends-p (x y)
154 "Check whether X may depend on any of the symbols in Y."
155 (and (not (macroexp-const-p x))
156 (or (not (cl--safe-expr-p x)) (cl--expr-contains-any x y))))
158 ;;; Symbols.
160 (defvar cl--gensym-counter)
161 ;;;###autoload
162 (defun cl-gensym (&optional prefix)
163 "Generate a new uninterned symbol.
164 The name is made by appending a number to PREFIX, default \"G\"."
165 (let ((pfix (if (stringp prefix) prefix "G"))
166 (num (if (integerp prefix) prefix
167 (prog1 cl--gensym-counter
168 (setq cl--gensym-counter (1+ cl--gensym-counter))))))
169 (make-symbol (format "%s%d" pfix num))))
171 ;;;###autoload
172 (defun cl-gentemp (&optional prefix)
173 "Generate a new interned symbol with a unique name.
174 The name is made by appending a number to PREFIX, default \"G\"."
175 (let ((pfix (if (stringp prefix) prefix "G"))
176 name)
177 (while (intern-soft (setq name (format "%s%d" pfix cl--gensym-counter)))
178 (setq cl--gensym-counter (1+ cl--gensym-counter)))
179 (intern name)))
182 ;;; Program structure.
184 (def-edebug-spec cl-declarations
185 (&rest ("cl-declare" &rest sexp)))
187 (def-edebug-spec cl-declarations-or-string
188 (&or stringp cl-declarations))
190 (def-edebug-spec cl-lambda-list
191 (([&rest arg]
192 [&optional ["&optional" cl-&optional-arg &rest cl-&optional-arg]]
193 [&optional ["&rest" arg]]
194 [&optional ["&key" [cl-&key-arg &rest cl-&key-arg]
195 &optional "&allow-other-keys"]]
196 [&optional ["&aux" &rest
197 &or (symbolp &optional def-form) symbolp]]
200 (def-edebug-spec cl-&optional-arg
201 (&or (arg &optional def-form arg) arg))
203 (def-edebug-spec cl-&key-arg
204 (&or ([&or (symbolp arg) arg] &optional def-form arg) arg))
206 ;;;###autoload
207 (defmacro cl-defun (name args &rest body)
208 "Define NAME as a function.
209 Like normal `defun', except ARGLIST allows full Common Lisp conventions,
210 and BODY is implicitly surrounded by (cl-block NAME ...).
212 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
213 (declare (debug
214 ;; Same as defun but use cl-lambda-list.
215 (&define [&or name ("cl-setf" :name cl-setf name)]
216 cl-lambda-list
217 cl-declarations-or-string
218 [&optional ("interactive" interactive)]
219 def-body))
220 (doc-string 3)
221 (indent 2))
222 (let* ((res (cl--transform-lambda (cons args body) name))
223 (form `(defun ,name ,@(cdr res))))
224 (if (car res) `(progn ,(car res) ,form) form)))
226 ;; The lambda list for macros is different from that of normal lambdas.
227 ;; Note that &environment is only allowed as first or last items in the
228 ;; top level list.
230 (def-edebug-spec cl-macro-list
231 (([&optional "&environment" arg]
232 [&rest cl-macro-arg]
233 [&optional ["&optional" &rest
234 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
235 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
236 [&optional ["&key" [&rest
237 [&or ([&or (symbolp cl-macro-arg) arg]
238 &optional def-form cl-macro-arg)
239 arg]]
240 &optional "&allow-other-keys"]]
241 [&optional ["&aux" &rest
242 &or (symbolp &optional def-form) symbolp]]
243 [&optional "&environment" arg]
246 (def-edebug-spec cl-macro-arg
247 (&or arg cl-macro-list1))
249 (def-edebug-spec cl-macro-list1
250 (([&optional "&whole" arg] ;; only allowed at lower levels
251 [&rest cl-macro-arg]
252 [&optional ["&optional" &rest
253 &or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
254 [&optional [[&or "&rest" "&body"] cl-macro-arg]]
255 [&optional ["&key" [&rest
256 [&or ([&or (symbolp cl-macro-arg) arg]
257 &optional def-form cl-macro-arg)
258 arg]]
259 &optional "&allow-other-keys"]]
260 [&optional ["&aux" &rest
261 &or (symbolp &optional def-form) symbolp]]
262 . [&or arg nil])))
264 ;;;###autoload
265 (defmacro cl-defmacro (name args &rest body)
266 "Define NAME as a macro.
267 Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
268 and BODY is implicitly surrounded by (cl-block NAME ...).
270 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
271 (declare (debug
272 (&define name cl-macro-list cl-declarations-or-string def-body))
273 (doc-string 3)
274 (indent 2))
275 (let* ((res (cl--transform-lambda (cons args body) name))
276 (form `(defmacro ,name ,@(cdr res))))
277 (if (car res) `(progn ,(car res) ,form) form)))
279 (def-edebug-spec cl-lambda-expr
280 (&define ("lambda" cl-lambda-list
281 ;;cl-declarations-or-string
282 ;;[&optional ("interactive" interactive)]
283 def-body)))
285 ;; Redefine function-form to also match cl-function
286 (def-edebug-spec function-form
287 ;; form at the end could also handle "function",
288 ;; but recognize it specially to avoid wrapping function forms.
289 (&or ([&or "quote" "function"] &or symbolp lambda-expr)
290 ("cl-function" cl-function)
291 form))
293 ;;;###autoload
294 (defmacro cl-function (func)
295 "Introduce a function.
296 Like normal `function', except that if argument is a lambda form,
297 its argument list allows full Common Lisp conventions."
298 (declare (debug (&or symbolp cl-lambda-expr)))
299 (if (eq (car-safe func) 'lambda)
300 (let* ((res (cl--transform-lambda (cdr func) 'cl-none))
301 (form `(function (lambda . ,(cdr res)))))
302 (if (car res) `(progn ,(car res) ,form) form))
303 `(function ,func)))
305 (defun cl--transform-function-property (func prop form)
306 (let ((res (cl--transform-lambda form func)))
307 `(progn ,@(cdr (cdr (car res)))
308 (put ',func ',prop #'(lambda . ,(cdr res))))))
310 (defconst cl-lambda-list-keywords
311 '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
313 (defvar cl-macro-environment nil
314 "Keep the list of currently active macros.
315 It is a list of elements of the form either:
316 - (SYMBOL . FUNCTION) where FUNCTION is the macro expansion function.
317 - (SYMBOL-NAME . EXPANSION) where SYMBOL-NAME is the name of a symbol macro.")
318 (defvar cl-bind-block) (defvar cl-bind-defs) (defvar cl-bind-enquote)
319 (defvar cl-bind-inits) (defvar cl-bind-lets) (defvar cl-bind-forms)
321 (declare-function help-add-fundoc-usage "help-fns" (docstring arglist))
323 (defun cl--make-usage-var (x)
324 "X can be a var or a (destructuring) lambda-list."
325 (cond
326 ((symbolp x) (make-symbol (upcase (symbol-name x))))
327 ((consp x) (cl--make-usage-args x))
328 (t x)))
330 (defun cl--make-usage-args (arglist)
331 ;; `orig-args' can contain &cl-defs (an internal
332 ;; CL thingy I don't understand), so remove it.
333 (let ((x (memq '&cl-defs arglist)))
334 (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
335 (let ((state nil))
336 (mapcar (lambda (x)
337 (cond
338 ((symbolp x)
339 (if (eq ?\& (aref (symbol-name x) 0))
340 (setq state x)
341 (make-symbol (upcase (symbol-name x)))))
342 ((not (consp x)) x)
343 ((memq state '(nil &rest)) (cl--make-usage-args x))
344 (t ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
345 (cl-list*
346 (if (and (consp (car x)) (eq state '&key))
347 (list (caar x) (cl--make-usage-var (nth 1 (car x))))
348 (cl--make-usage-var (car x)))
349 (nth 1 x) ;INITFORM.
350 (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
351 ))))
352 arglist)))
354 (defun cl--transform-lambda (form cl-bind-block)
355 (let* ((args (car form)) (body (cdr form)) (orig-args args)
356 (cl-bind-defs nil) (cl-bind-enquote nil)
357 (cl-bind-inits nil) (cl-bind-lets nil) (cl-bind-forms nil)
358 (header nil) (simple-args nil))
359 (while (or (stringp (car body))
360 (memq (car-safe (car body)) '(interactive cl-declare)))
361 (push (pop body) header))
362 (setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
363 (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
364 (if (setq cl-bind-defs (cadr (memq '&cl-defs args)))
365 (setq args (delq '&cl-defs (delq cl-bind-defs args))
366 cl-bind-defs (cadr cl-bind-defs)))
367 (if (setq cl-bind-enquote (memq '&cl-quote args))
368 (setq args (delq '&cl-quote args)))
369 (if (memq '&whole args) (error "&whole not currently implemented"))
370 (let* ((p (memq '&environment args)) (v (cadr p)))
371 (if p (setq args (nconc (delq (car p) (delq v args))
372 (list '&aux (list v 'cl-macro-environment))))))
373 (while (and args (symbolp (car args))
374 (not (memq (car args) '(nil &rest &body &key &aux)))
375 (not (and (eq (car args) '&optional)
376 (or cl-bind-defs (consp (cadr args))))))
377 (push (pop args) simple-args))
378 (or (eq cl-bind-block 'cl-none)
379 (setq body (list `(cl-block ,cl-bind-block ,@body))))
380 (if (null args)
381 (cl-list* nil (nreverse simple-args) (nconc (nreverse header) body))
382 (if (memq '&optional simple-args) (push '&optional args))
383 (cl--do-arglist args nil (- (length simple-args)
384 (if (memq '&optional simple-args) 1 0)))
385 (setq cl-bind-lets (nreverse cl-bind-lets))
386 (cl-list* (and cl-bind-inits `(cl-eval-when (compile load eval)
387 ,@(nreverse cl-bind-inits)))
388 (nconc (nreverse simple-args)
389 (list '&rest (car (pop cl-bind-lets))))
390 (nconc (let ((hdr (nreverse header)))
391 ;; Macro expansion can take place in the middle of
392 ;; apparently harmless computation, so it should not
393 ;; touch the match-data.
394 (save-match-data
395 (require 'help-fns)
396 (cons (help-add-fundoc-usage
397 (if (stringp (car hdr)) (pop hdr))
398 (format "%S"
399 (cons 'fn
400 (cl--make-usage-args orig-args))))
401 hdr)))
402 (list `(let* ,cl-bind-lets
403 ,@(nreverse cl-bind-forms)
404 ,@body)))))))
406 (defun cl--do-arglist (args expr &optional num) ; uses bind-*
407 (if (nlistp args)
408 (if (or (memq args cl-lambda-list-keywords) (not (symbolp args)))
409 (error "Invalid argument name: %s" args)
410 (push (list args expr) cl-bind-lets))
411 (setq args (cl-copy-list args))
412 (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
413 (let ((p (memq '&body args))) (if p (setcar p '&rest)))
414 (if (memq '&environment args) (error "&environment used incorrectly"))
415 (let ((save-args args)
416 (restarg (memq '&rest args))
417 (safety (if (cl-compiling-file) cl-optimize-safety 3))
418 (keys nil)
419 (laterarg nil) (exactarg nil) minarg)
420 (or num (setq num 0))
421 (if (listp (cadr restarg))
422 (setq restarg (make-symbol "--cl-rest--"))
423 (setq restarg (cadr restarg)))
424 (push (list restarg expr) cl-bind-lets)
425 (if (eq (car args) '&whole)
426 (push (list (cl-pop2 args) restarg) cl-bind-lets))
427 (let ((p args))
428 (setq minarg restarg)
429 (while (and p (not (memq (car p) cl-lambda-list-keywords)))
430 (or (eq p args) (setq minarg (list 'cdr minarg)))
431 (setq p (cdr p)))
432 (if (memq (car p) '(nil &aux))
433 (setq minarg `(= (length ,restarg)
434 ,(length (cl-ldiff args p)))
435 exactarg (not (eq args p)))))
436 (while (and args (not (memq (car args) cl-lambda-list-keywords)))
437 (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
438 restarg)))
439 (cl--do-arglist
440 (pop args)
441 (if (or laterarg (= safety 0)) poparg
442 `(if ,minarg ,poparg
443 (signal 'wrong-number-of-arguments
444 (list ,(and (not (eq cl-bind-block 'cl-none))
445 `',cl-bind-block)
446 (length ,restarg)))))))
447 (setq num (1+ num) laterarg t))
448 (while (and (eq (car args) '&optional) (pop args))
449 (while (and args (not (memq (car args) cl-lambda-list-keywords)))
450 (let ((arg (pop args)))
451 (or (consp arg) (setq arg (list arg)))
452 (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
453 (let ((def (if (cdr arg) (nth 1 arg)
454 (or (car cl-bind-defs)
455 (nth 1 (assq (car arg) cl-bind-defs)))))
456 (poparg `(pop ,restarg)))
457 (and def cl-bind-enquote (setq def `',def))
458 (cl--do-arglist (car arg)
459 (if def `(if ,restarg ,poparg ,def) poparg))
460 (setq num (1+ num))))))
461 (if (eq (car args) '&rest)
462 (let ((arg (cl-pop2 args)))
463 (if (consp arg) (cl--do-arglist arg restarg)))
464 (or (eq (car args) '&key) (= safety 0) exactarg
465 (push `(if ,restarg
466 (signal 'wrong-number-of-arguments
467 (list
468 ,(and (not (eq cl-bind-block 'cl-none))
469 `',cl-bind-block)
470 (+ ,num (length ,restarg)))))
471 cl-bind-forms)))
472 (while (and (eq (car args) '&key) (pop args))
473 (while (and args (not (memq (car args) cl-lambda-list-keywords)))
474 (let ((arg (pop args)))
475 (or (consp arg) (setq arg (list arg)))
476 (let* ((karg (if (consp (car arg)) (caar arg)
477 (intern (format ":%s" (car arg)))))
478 (varg (if (consp (car arg)) (cl-cadar arg) (car arg)))
479 (def (if (cdr arg) (cadr arg)
480 (or (car cl-bind-defs) (cadr (assq varg cl-bind-defs)))))
481 (look `(memq ',karg ,restarg)))
482 (and def cl-bind-enquote (setq def `',def))
483 (if (cddr arg)
484 (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
485 (val `(car (cdr ,temp))))
486 (cl--do-arglist temp look)
487 (cl--do-arglist varg
488 `(if ,temp
489 (prog1 ,val (setq ,temp t))
490 ,def)))
491 (cl--do-arglist
492 varg
493 `(car (cdr ,(if (null def)
494 look
495 `(or ,look
496 ,(if (eq (cl--const-expr-p def) t)
497 `'(nil ,(cl--const-expr-val def))
498 `(list nil ,def))))))))
499 (push karg keys)))))
500 (setq keys (nreverse keys))
501 (or (and (eq (car args) '&allow-other-keys) (pop args))
502 (null keys) (= safety 0)
503 (let* ((var (make-symbol "--cl-keys--"))
504 (allow '(:allow-other-keys))
505 (check `(while ,var
506 (cond
507 ((memq (car ,var) ',(append keys allow))
508 (setq ,var (cdr (cdr ,var))))
509 ((car (cdr (memq (quote ,@allow) ,restarg)))
510 (setq ,var nil))
512 (error
513 ,(format "Keyword argument %%s not one of %s"
514 keys)
515 (car ,var)))))))
516 (push `(let ((,var ,restarg)) ,check) cl-bind-forms)))
517 (while (and (eq (car args) '&aux) (pop args))
518 (while (and args (not (memq (car args) cl-lambda-list-keywords)))
519 (if (consp (car args))
520 (if (and cl-bind-enquote (cl-cadar args))
521 (cl--do-arglist (caar args)
522 `',(cadr (pop args)))
523 (cl--do-arglist (caar args) (cadr (pop args))))
524 (cl--do-arglist (pop args) nil))))
525 (if args (error "Malformed argument list %s" save-args)))))
527 (defun cl--arglist-args (args)
528 (if (nlistp args) (list args)
529 (let ((res nil) (kind nil) arg)
530 (while (consp args)
531 (setq arg (pop args))
532 (if (memq arg cl-lambda-list-keywords) (setq kind arg)
533 (if (eq arg '&cl-defs) (pop args)
534 (and (consp arg) kind (setq arg (car arg)))
535 (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
536 (setq res (nconc res (cl--arglist-args arg))))))
537 (nconc res (and args (list args))))))
539 ;;;###autoload
540 (defmacro cl-destructuring-bind (args expr &rest body)
541 (declare (indent 2)
542 (debug (&define cl-macro-list def-form cl-declarations def-body)))
543 (let* ((cl-bind-lets nil) (cl-bind-forms nil) (cl-bind-inits nil)
544 (cl-bind-defs nil) (cl-bind-block 'cl-none) (cl-bind-enquote nil))
545 (cl--do-arglist (or args '(&aux)) expr)
546 (append '(progn) cl-bind-inits
547 (list `(let* ,(nreverse cl-bind-lets)
548 ,@(nreverse cl-bind-forms) ,@body)))))
551 ;;; The `cl-eval-when' form.
553 (defvar cl-not-toplevel nil)
555 ;;;###autoload
556 (defmacro cl-eval-when (when &rest body)
557 "Control when BODY is evaluated.
558 If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
559 If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
560 If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.
562 \(fn (WHEN...) BODY...)"
563 (declare (indent 1) (debug ((&rest &or "compile" "load" "eval") body)))
564 (if (and (fboundp 'cl-compiling-file) (cl-compiling-file)
565 (not cl-not-toplevel) (not (boundp 'for-effect))) ; horrible kludge
566 (let ((comp (or (memq 'compile when) (memq :compile-toplevel when)))
567 (cl-not-toplevel t))
568 (if (or (memq 'load when) (memq :load-toplevel when))
569 (if comp (cons 'progn (mapcar 'cl--compile-time-too body))
570 `(if nil nil ,@body))
571 (progn (if comp (eval (cons 'progn body))) nil)))
572 (and (or (memq 'eval when) (memq :execute when))
573 (cons 'progn body))))
575 (defun cl--compile-time-too (form)
576 (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
577 (setq form (macroexpand
578 form (cons '(cl-eval-when) byte-compile-macro-environment))))
579 (cond ((eq (car-safe form) 'progn)
580 (cons 'progn (mapcar 'cl--compile-time-too (cdr form))))
581 ((eq (car-safe form) 'cl-eval-when)
582 (let ((when (nth 1 form)))
583 (if (or (memq 'eval when) (memq :execute when))
584 `(cl-eval-when (compile ,@when) ,@(cddr form))
585 form)))
586 (t (eval form) form)))
588 ;;;###autoload
589 (defmacro cl-load-time-value (form &optional read-only)
590 "Like `progn', but evaluates the body at load time.
591 The result of the body appears to the compiler as a quoted constant."
592 (declare (debug (form &optional sexp)))
593 (if (cl-compiling-file)
594 (let* ((temp (cl-gentemp "--cl-load-time--"))
595 (set `(set ',temp ,form)))
596 (if (and (fboundp 'byte-compile-file-form-defmumble)
597 (boundp 'this-kind) (boundp 'that-one))
598 (fset 'byte-compile-file-form
599 `(lambda (form)
600 (fset 'byte-compile-file-form
601 ',(symbol-function 'byte-compile-file-form))
602 (byte-compile-file-form ',set)
603 (byte-compile-file-form form)))
604 (print set (symbol-value 'byte-compile--outbuffer)))
605 `(symbol-value ',temp))
606 `',(eval form)))
609 ;;; Conditional control structures.
611 ;;;###autoload
612 (defmacro cl-case (expr &rest clauses)
613 "Eval EXPR and choose among clauses on that value.
614 Each clause looks like (KEYLIST BODY...). EXPR is evaluated and compared
615 against each key in each KEYLIST; the corresponding BODY is evaluated.
616 If no clause succeeds, cl-case returns nil. A single atom may be used in
617 place of a KEYLIST of one atom. A KEYLIST of t or `otherwise' is
618 allowed only in the final clause, and matches if no other keys match.
619 Key values are compared by `eql'.
620 \n(fn EXPR (KEYLIST BODY...)...)"
621 (declare (indent 1) (debug (form &rest (sexp body))))
622 (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
623 (head-list nil)
624 (body (cons
625 'cond
626 (mapcar
627 (function
628 (lambda (c)
629 (cons (cond ((memq (car c) '(t otherwise)) t)
630 ((eq (car c) 'cl--ecase-error-flag)
631 `(error "cl-ecase failed: %s, %s"
632 ,temp ',(reverse head-list)))
633 ((listp (car c))
634 (setq head-list (append (car c) head-list))
635 `(cl-member ,temp ',(car c)))
637 (if (memq (car c) head-list)
638 (error "Duplicate key in case: %s"
639 (car c)))
640 (push (car c) head-list)
641 `(eql ,temp ',(car c))))
642 (or (cdr c) '(nil)))))
643 clauses))))
644 (if (eq temp expr) body
645 `(let ((,temp ,expr)) ,body))))
647 ;;;###autoload
648 (defmacro cl-ecase (expr &rest clauses)
649 "Like `cl-case', but error if no cl-case fits.
650 `otherwise'-clauses are not allowed.
651 \n(fn EXPR (KEYLIST BODY...)...)"
652 (declare (indent 1) (debug cl-case))
653 `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
655 ;;;###autoload
656 (defmacro cl-typecase (expr &rest clauses)
657 "Evals EXPR, chooses among clauses on that value.
658 Each clause looks like (TYPE BODY...). EXPR is evaluated and, if it
659 satisfies TYPE, the corresponding BODY is evaluated. If no clause succeeds,
660 cl-typecase returns nil. A TYPE of t or `otherwise' is allowed only in the
661 final clause, and matches if no other keys match.
662 \n(fn EXPR (TYPE BODY...)...)"
663 (declare (indent 1)
664 (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
665 (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
666 (type-list nil)
667 (body (cons
668 'cond
669 (mapcar
670 (function
671 (lambda (c)
672 (cons (cond ((eq (car c) 'otherwise) t)
673 ((eq (car c) 'cl--ecase-error-flag)
674 `(error "cl-etypecase failed: %s, %s"
675 ,temp ',(reverse type-list)))
677 (push (car c) type-list)
678 (cl--make-type-test temp (car c))))
679 (or (cdr c) '(nil)))))
680 clauses))))
681 (if (eq temp expr) body
682 `(let ((,temp ,expr)) ,body))))
684 ;;;###autoload
685 (defmacro cl-etypecase (expr &rest clauses)
686 "Like `cl-typecase', but error if no case fits.
687 `otherwise'-clauses are not allowed.
688 \n(fn EXPR (TYPE BODY...)...)"
689 (declare (indent 1) (debug cl-typecase))
690 `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
693 ;;; Blocks and exits.
695 ;;;###autoload
696 (defmacro cl-block (name &rest body)
697 "Define a lexically-scoped block named NAME.
698 NAME may be any symbol. Code inside the BODY forms can call `cl-return-from'
699 to jump prematurely out of the block. This differs from `catch' and `throw'
700 in two respects: First, the NAME is an unevaluated symbol rather than a
701 quoted symbol or other form; and second, NAME is lexically rather than
702 dynamically scoped: Only references to it within BODY will work. These
703 references may appear inside macro expansions, but not inside functions
704 called from BODY."
705 (declare (indent 1) (debug (symbolp body)))
706 (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
707 `(cl-block-wrapper
708 (catch ',(intern (format "--cl-block-%s--" name))
709 ,@body))))
711 ;;;###autoload
712 (defmacro cl-return (&optional result)
713 "Return from the block named nil.
714 This is equivalent to `(cl-return-from nil RESULT)'."
715 (declare (debug (&optional form)))
716 `(cl-return-from nil ,result))
718 ;;;###autoload
719 (defmacro cl-return-from (name &optional result)
720 "Return from the block named NAME.
721 This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
722 returning RESULT from that form (or nil if RESULT is omitted).
723 This is compatible with Common Lisp, but note that `defun' and
724 `defmacro' do not create implicit blocks as they do in Common Lisp."
725 (declare (indent 1) (debug (symbolp &optional form)))
726 (let ((name2 (intern (format "--cl-block-%s--" name))))
727 `(cl-block-throw ',name2 ,result)))
730 ;;; The "cl-loop" macro.
732 (defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
733 (defvar cl--loop-bindings) (defvar cl--loop-body) (defvar cl--loop-destr-temps)
734 (defvar cl--loop-finally) (defvar cl--loop-finish-flag)
735 (defvar cl--loop-first-flag)
736 (defvar cl--loop-initially) (defvar cl--loop-map-form) (defvar cl--loop-name)
737 (defvar cl--loop-result) (defvar cl--loop-result-explicit)
738 (defvar cl--loop-result-var) (defvar cl--loop-steps) (defvar cl--loop-symbol-macs)
740 ;;;###autoload
741 (defmacro cl-loop (&rest cl--loop-args)
742 "The Common Lisp `cl-loop' macro.
743 Valid clauses are:
744 for VAR from/upfrom/downfrom NUM to/upto/downto/above/below NUM by NUM,
745 for VAR in LIST by FUNC, for VAR on LIST by FUNC, for VAR = INIT then EXPR,
746 for VAR across ARRAY, repeat NUM, with VAR = INIT, while COND, until COND,
747 always COND, never COND, thereis COND, collect EXPR into VAR,
748 append EXPR into VAR, nconc EXPR into VAR, sum EXPR into VAR,
749 count EXPR into VAR, maximize EXPR into VAR, minimize EXPR into VAR,
750 if COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
751 unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
752 do EXPRS..., initially EXPRS..., finally EXPRS..., return EXPR,
753 finally return EXPR, named NAME.
755 \(fn CLAUSE...)"
756 (declare (debug (&rest &or symbolp form)))
757 (if (not (memq t (mapcar 'symbolp (delq nil (delq t (cl-copy-list cl--loop-args))))))
758 `(cl-block nil (while t ,@cl--loop-args))
759 (let ((cl--loop-name nil) (cl--loop-bindings nil)
760 (cl--loop-body nil) (cl--loop-steps nil)
761 (cl--loop-result nil) (cl--loop-result-explicit nil)
762 (cl--loop-result-var nil) (cl--loop-finish-flag nil)
763 (cl--loop-accum-var nil) (cl--loop-accum-vars nil)
764 (cl--loop-initially nil) (cl--loop-finally nil)
765 (cl--loop-map-form nil) (cl--loop-first-flag nil)
766 (cl--loop-destr-temps nil) (cl--loop-symbol-macs nil))
767 (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
768 (while (not (eq (car cl--loop-args) 'cl-end-loop)) (cl-parse-loop-clause))
769 (if cl--loop-finish-flag
770 (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
771 (if cl--loop-first-flag
772 (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
773 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
774 (let* ((epilogue (nconc (nreverse cl--loop-finally)
775 (list (or cl--loop-result-explicit cl--loop-result))))
776 (ands (cl--loop-build-ands (nreverse cl--loop-body)))
777 (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
778 (body (append
779 (nreverse cl--loop-initially)
780 (list (if cl--loop-map-form
781 `(cl-block --cl-finish--
782 ,(cl-subst
783 (if (eq (car ands) t) while-body
784 (cons `(or ,(car ands)
785 (cl-return-from --cl-finish--
786 nil))
787 while-body))
788 '--cl-map cl--loop-map-form))
789 `(while ,(car ands) ,@while-body)))
790 (if cl--loop-finish-flag
791 (if (equal epilogue '(nil)) (list cl--loop-result-var)
792 `((if ,cl--loop-finish-flag
793 (progn ,@epilogue) ,cl--loop-result-var)))
794 epilogue))))
795 (if cl--loop-result-var (push (list cl--loop-result-var) cl--loop-bindings))
796 (while cl--loop-bindings
797 (if (cdar cl--loop-bindings)
798 (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
799 (let ((lets nil))
800 (while (and cl--loop-bindings
801 (not (cdar cl--loop-bindings)))
802 (push (car (pop cl--loop-bindings)) lets))
803 (setq body (list (cl--loop-let lets body nil))))))
804 (if cl--loop-symbol-macs
805 (setq body (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
806 `(cl-block ,cl--loop-name ,@body)))))
808 ;; Below is a complete spec for cl-loop, in several parts that correspond
809 ;; to the syntax given in CLtL2. The specs do more than specify where
810 ;; the forms are; it also specifies, as much as Edebug allows, all the
811 ;; syntactically valid cl-loop clauses. The disadvantage of this
812 ;; completeness is rigidity, but the "for ... being" clause allows
813 ;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].
815 ;; (def-edebug-spec cl-loop
816 ;; ([&optional ["named" symbolp]]
817 ;; [&rest
818 ;; &or
819 ;; ["repeat" form]
820 ;; loop-for-as
821 ;; loop-with
822 ;; loop-initial-final]
823 ;; [&rest loop-clause]
824 ;; ))
826 ;; (def-edebug-spec loop-with
827 ;; ("with" loop-var
828 ;; loop-type-spec
829 ;; [&optional ["=" form]]
830 ;; &rest ["and" loop-var
831 ;; loop-type-spec
832 ;; [&optional ["=" form]]]))
834 ;; (def-edebug-spec loop-for-as
835 ;; ([&or "for" "as"] loop-for-as-subclause
836 ;; &rest ["and" loop-for-as-subclause]))
838 ;; (def-edebug-spec loop-for-as-subclause
839 ;; (loop-var
840 ;; loop-type-spec
841 ;; &or
842 ;; [[&or "in" "on" "in-ref" "across-ref"]
843 ;; form &optional ["by" function-form]]
845 ;; ["=" form &optional ["then" form]]
846 ;; ["across" form]
847 ;; ["being"
848 ;; [&or "the" "each"]
849 ;; &or
850 ;; [[&or "element" "elements"]
851 ;; [&or "of" "in" "of-ref"] form
852 ;; &optional "using" ["index" symbolp]];; is this right?
853 ;; [[&or "hash-key" "hash-keys"
854 ;; "hash-value" "hash-values"]
855 ;; [&or "of" "in"]
856 ;; hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
857 ;; "hash-key" "hash-keys"] sexp)]]
859 ;; [[&or "symbol" "present-symbol" "external-symbol"
860 ;; "symbols" "present-symbols" "external-symbols"]
861 ;; [&or "in" "of"] package-p]
863 ;; ;; Extensions for Emacs Lisp, including Lucid Emacs.
864 ;; [[&or "frame" "frames"
865 ;; "screen" "screens"
866 ;; "buffer" "buffers"]]
868 ;; [[&or "window" "windows"]
869 ;; [&or "of" "in"] form]
871 ;; [[&or "overlay" "overlays"
872 ;; "extent" "extents"]
873 ;; [&or "of" "in"] form
874 ;; &optional [[&or "from" "to"] form]]
876 ;; [[&or "interval" "intervals"]
877 ;; [&or "in" "of"] form
878 ;; &optional [[&or "from" "to"] form]
879 ;; ["property" form]]
881 ;; [[&or "key-code" "key-codes"
882 ;; "key-seq" "key-seqs"
883 ;; "key-binding" "key-bindings"]
884 ;; [&or "in" "of"] form
885 ;; &optional ["using" ([&or "key-code" "key-codes"
886 ;; "key-seq" "key-seqs"
887 ;; "key-binding" "key-bindings"]
888 ;; sexp)]]
889 ;; ;; For arbitrary extensions, recognize anything else.
890 ;; [symbolp &rest &or symbolp form]
891 ;; ]
893 ;; ;; arithmetic - must be last since all parts are optional.
894 ;; [[&optional [[&or "from" "downfrom" "upfrom"] form]]
895 ;; [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
896 ;; [&optional ["by" form]]
897 ;; ]))
899 ;; (def-edebug-spec loop-initial-final
900 ;; (&or ["initially"
901 ;; ;; [&optional &or "do" "doing"] ;; CLtL2 doesn't allow this.
902 ;; &rest loop-non-atomic-expr]
903 ;; ["finally" &or
904 ;; [[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
905 ;; ["return" form]]))
907 ;; (def-edebug-spec loop-and-clause
908 ;; (loop-clause &rest ["and" loop-clause]))
910 ;; (def-edebug-spec loop-clause
911 ;; (&or
912 ;; [[&or "while" "until" "always" "never" "thereis"] form]
914 ;; [[&or "collect" "collecting"
915 ;; "append" "appending"
916 ;; "nconc" "nconcing"
917 ;; "concat" "vconcat"] form
918 ;; [&optional ["into" loop-var]]]
920 ;; [[&or "count" "counting"
921 ;; "sum" "summing"
922 ;; "maximize" "maximizing"
923 ;; "minimize" "minimizing"] form
924 ;; [&optional ["into" loop-var]]
925 ;; loop-type-spec]
927 ;; [[&or "if" "when" "unless"]
928 ;; form loop-and-clause
929 ;; [&optional ["else" loop-and-clause]]
930 ;; [&optional "end"]]
932 ;; [[&or "do" "doing"] &rest loop-non-atomic-expr]
934 ;; ["return" form]
935 ;; loop-initial-final
936 ;; ))
938 ;; (def-edebug-spec loop-non-atomic-expr
939 ;; ([&not atom] form))
941 ;; (def-edebug-spec loop-var
942 ;; ;; The symbolp must be last alternative to recognize e.g. (a b . c)
943 ;; ;; loop-var =>
944 ;; ;; (loop-var . [&or nil loop-var])
945 ;; ;; (symbolp . [&or nil loop-var])
946 ;; ;; (symbolp . loop-var)
947 ;; ;; (symbolp . (symbolp . [&or nil loop-var]))
948 ;; ;; (symbolp . (symbolp . loop-var))
949 ;; ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
950 ;; (&or (loop-var . [&or nil loop-var]) [gate symbolp]))
952 ;; (def-edebug-spec loop-type-spec
953 ;; (&optional ["of-type" loop-d-type-spec]))
955 ;; (def-edebug-spec loop-d-type-spec
956 ;; (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))
960 (defun cl-parse-loop-clause () ; uses loop-*
961 (let ((word (pop cl--loop-args))
962 (hash-types '(hash-key hash-keys hash-value hash-values))
963 (key-types '(key-code key-codes key-seq key-seqs
964 key-binding key-bindings)))
965 (cond
967 ((null cl--loop-args)
968 (error "Malformed `cl-loop' macro"))
970 ((eq word 'named)
971 (setq cl--loop-name (pop cl--loop-args)))
973 ((eq word 'initially)
974 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
975 (or (consp (car cl--loop-args)) (error "Syntax error on `initially' clause"))
976 (while (consp (car cl--loop-args))
977 (push (pop cl--loop-args) cl--loop-initially)))
979 ((eq word 'finally)
980 (if (eq (car cl--loop-args) 'return)
981 (setq cl--loop-result-explicit (or (cl-pop2 cl--loop-args) '(quote nil)))
982 (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
983 (or (consp (car cl--loop-args)) (error "Syntax error on `finally' clause"))
984 (if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
985 (setq cl--loop-result-explicit (or (nth 1 (pop cl--loop-args)) '(quote nil)))
986 (while (consp (car cl--loop-args))
987 (push (pop cl--loop-args) cl--loop-finally)))))
989 ((memq word '(for as))
990 (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
991 (ands nil))
992 (while
993 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
994 ;; (not (eq (symbol-name var1) (symbol-name var2))) because
995 ;; these vars get added to the macro-environment.
996 (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
997 (setq word (pop cl--loop-args))
998 (if (eq word 'being) (setq word (pop cl--loop-args)))
999 (if (memq word '(the each)) (setq word (pop cl--loop-args)))
1000 (if (memq word '(buffer buffers))
1001 (setq word 'in cl--loop-args (cons '(buffer-list) cl--loop-args)))
1002 (cond
1004 ((memq word '(from downfrom upfrom to downto upto
1005 above below by))
1006 (push word cl--loop-args)
1007 (if (memq (car cl--loop-args) '(downto above))
1008 (error "Must specify `from' value for downward cl-loop"))
1009 (let* ((down (or (eq (car cl--loop-args) 'downfrom)
1010 (memq (cl-caddr cl--loop-args) '(downto above))))
1011 (excl (or (memq (car cl--loop-args) '(above below))
1012 (memq (cl-caddr cl--loop-args) '(above below))))
1013 (start (and (memq (car cl--loop-args) '(from upfrom downfrom))
1014 (cl-pop2 cl--loop-args)))
1015 (end (and (memq (car cl--loop-args)
1016 '(to upto downto above below))
1017 (cl-pop2 cl--loop-args)))
1018 (step (and (eq (car cl--loop-args) 'by) (cl-pop2 cl--loop-args)))
1019 (end-var (and (not (macroexp-const-p end))
1020 (make-symbol "--cl-var--")))
1021 (step-var (and (not (macroexp-const-p step))
1022 (make-symbol "--cl-var--"))))
1023 (and step (numberp step) (<= step 0)
1024 (error "Loop `by' value is not positive: %s" step))
1025 (push (list var (or start 0)) loop-for-bindings)
1026 (if end-var (push (list end-var end) loop-for-bindings))
1027 (if step-var (push (list step-var step)
1028 loop-for-bindings))
1029 (if end
1030 (push (list
1031 (if down (if excl '> '>=) (if excl '< '<=))
1032 var (or end-var end)) cl--loop-body))
1033 (push (list var (list (if down '- '+) var
1034 (or step-var step 1)))
1035 loop-for-steps)))
1037 ((memq word '(in in-ref on))
1038 (let* ((on (eq word 'on))
1039 (temp (if (and on (symbolp var))
1040 var (make-symbol "--cl-var--"))))
1041 (push (list temp (pop cl--loop-args)) loop-for-bindings)
1042 (push `(consp ,temp) cl--loop-body)
1043 (if (eq word 'in-ref)
1044 (push (list var `(car ,temp)) cl--loop-symbol-macs)
1045 (or (eq temp var)
1046 (progn
1047 (push (list var nil) loop-for-bindings)
1048 (push (list var (if on temp `(car ,temp)))
1049 loop-for-sets))))
1050 (push (list temp
1051 (if (eq (car cl--loop-args) 'by)
1052 (let ((step (cl-pop2 cl--loop-args)))
1053 (if (and (memq (car-safe step)
1054 '(quote function
1055 cl-function))
1056 (symbolp (nth 1 step)))
1057 (list (nth 1 step) temp)
1058 `(funcall ,step ,temp)))
1059 `(cdr ,temp)))
1060 loop-for-steps)))
1062 ((eq word '=)
1063 (let* ((start (pop cl--loop-args))
1064 (then (if (eq (car cl--loop-args) 'then) (cl-pop2 cl--loop-args) start)))
1065 (push (list var nil) loop-for-bindings)
1066 (if (or ands (eq (car cl--loop-args) 'and))
1067 (progn
1068 (push `(,var
1069 (if ,(or cl--loop-first-flag
1070 (setq cl--loop-first-flag
1071 (make-symbol "--cl-var--")))
1072 ,start ,var))
1073 loop-for-sets)
1074 (push (list var then) loop-for-steps))
1075 (push (list var
1076 (if (eq start then) start
1077 `(if ,(or cl--loop-first-flag
1078 (setq cl--loop-first-flag
1079 (make-symbol "--cl-var--")))
1080 ,start ,then)))
1081 loop-for-sets))))
1083 ((memq word '(across across-ref))
1084 (let ((temp-vec (make-symbol "--cl-vec--"))
1085 (temp-idx (make-symbol "--cl-idx--")))
1086 (push (list temp-vec (pop cl--loop-args)) loop-for-bindings)
1087 (push (list temp-idx -1) loop-for-bindings)
1088 (push `(< (setq ,temp-idx (1+ ,temp-idx))
1089 (length ,temp-vec)) cl--loop-body)
1090 (if (eq word 'across-ref)
1091 (push (list var `(aref ,temp-vec ,temp-idx))
1092 cl--loop-symbol-macs)
1093 (push (list var nil) loop-for-bindings)
1094 (push (list var `(aref ,temp-vec ,temp-idx))
1095 loop-for-sets))))
1097 ((memq word '(element elements))
1098 (let ((ref (or (memq (car cl--loop-args) '(in-ref of-ref))
1099 (and (not (memq (car cl--loop-args) '(in of)))
1100 (error "Expected `of'"))))
1101 (seq (cl-pop2 cl--loop-args))
1102 (temp-seq (make-symbol "--cl-seq--"))
1103 (temp-idx (if (eq (car cl--loop-args) 'using)
1104 (if (and (= (length (cadr cl--loop-args)) 2)
1105 (eq (cl-caadr cl--loop-args) 'index))
1106 (cadr (cl-pop2 cl--loop-args))
1107 (error "Bad `using' clause"))
1108 (make-symbol "--cl-idx--"))))
1109 (push (list temp-seq seq) loop-for-bindings)
1110 (push (list temp-idx 0) loop-for-bindings)
1111 (if ref
1112 (let ((temp-len (make-symbol "--cl-len--")))
1113 (push (list temp-len `(length ,temp-seq))
1114 loop-for-bindings)
1115 (push (list var `(elt ,temp-seq temp-idx))
1116 cl--loop-symbol-macs)
1117 (push `(< ,temp-idx ,temp-len) cl--loop-body))
1118 (push (list var nil) loop-for-bindings)
1119 (push `(and ,temp-seq
1120 (or (consp ,temp-seq)
1121 (< ,temp-idx (length ,temp-seq))))
1122 cl--loop-body)
1123 (push (list var `(if (consp ,temp-seq)
1124 (pop ,temp-seq)
1125 (aref ,temp-seq ,temp-idx)))
1126 loop-for-sets))
1127 (push (list temp-idx `(1+ ,temp-idx))
1128 loop-for-steps)))
1130 ((memq word hash-types)
1131 (or (memq (car cl--loop-args) '(in of)) (error "Expected `of'"))
1132 (let* ((table (cl-pop2 cl--loop-args))
1133 (other (if (eq (car cl--loop-args) 'using)
1134 (if (and (= (length (cadr cl--loop-args)) 2)
1135 (memq (cl-caadr cl--loop-args) hash-types)
1136 (not (eq (cl-caadr cl--loop-args) word)))
1137 (cadr (cl-pop2 cl--loop-args))
1138 (error "Bad `using' clause"))
1139 (make-symbol "--cl-var--"))))
1140 (if (memq word '(hash-value hash-values))
1141 (setq var (prog1 other (setq other var))))
1142 (setq cl--loop-map-form
1143 `(maphash (lambda (,var ,other) . --cl-map) ,table))))
1145 ((memq word '(symbol present-symbol external-symbol
1146 symbols present-symbols external-symbols))
1147 (let ((ob (and (memq (car cl--loop-args) '(in of)) (cl-pop2 cl--loop-args))))
1148 (setq cl--loop-map-form
1149 `(mapatoms (lambda (,var) . --cl-map) ,ob))))
1151 ((memq word '(overlay overlays extent extents))
1152 (let ((buf nil) (from nil) (to nil))
1153 (while (memq (car cl--loop-args) '(in of from to))
1154 (cond ((eq (car cl--loop-args) 'from) (setq from (cl-pop2 cl--loop-args)))
1155 ((eq (car cl--loop-args) 'to) (setq to (cl-pop2 cl--loop-args)))
1156 (t (setq buf (cl-pop2 cl--loop-args)))))
1157 (setq cl--loop-map-form
1158 `(cl-map-extents
1159 (lambda (,var ,(make-symbol "--cl-var--"))
1160 (progn . --cl-map) nil)
1161 ,buf ,from ,to))))
1163 ((memq word '(interval intervals))
1164 (let ((buf nil) (prop nil) (from nil) (to nil)
1165 (var1 (make-symbol "--cl-var1--"))
1166 (var2 (make-symbol "--cl-var2--")))
1167 (while (memq (car cl--loop-args) '(in of property from to))
1168 (cond ((eq (car cl--loop-args) 'from) (setq from (cl-pop2 cl--loop-args)))
1169 ((eq (car cl--loop-args) 'to) (setq to (cl-pop2 cl--loop-args)))
1170 ((eq (car cl--loop-args) 'property)
1171 (setq prop (cl-pop2 cl--loop-args)))
1172 (t (setq buf (cl-pop2 cl--loop-args)))))
1173 (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
1174 (setq var1 (car var) var2 (cdr var))
1175 (push (list var `(cons ,var1 ,var2)) loop-for-sets))
1176 (setq cl--loop-map-form
1177 `(cl-map-intervals
1178 (lambda (,var1 ,var2) . --cl-map)
1179 ,buf ,prop ,from ,to))))
1181 ((memq word key-types)
1182 (or (memq (car cl--loop-args) '(in of)) (error "Expected `of'"))
1183 (let ((cl-map (cl-pop2 cl--loop-args))
1184 (other (if (eq (car cl--loop-args) 'using)
1185 (if (and (= (length (cadr cl--loop-args)) 2)
1186 (memq (cl-caadr cl--loop-args) key-types)
1187 (not (eq (cl-caadr cl--loop-args) word)))
1188 (cadr (cl-pop2 cl--loop-args))
1189 (error "Bad `using' clause"))
1190 (make-symbol "--cl-var--"))))
1191 (if (memq word '(key-binding key-bindings))
1192 (setq var (prog1 other (setq other var))))
1193 (setq cl--loop-map-form
1194 `(,(if (memq word '(key-seq key-seqs))
1195 'cl-map-keymap-recursively 'map-keymap)
1196 (lambda (,var ,other) . --cl-map) ,cl-map))))
1198 ((memq word '(frame frames screen screens))
1199 (let ((temp (make-symbol "--cl-var--")))
1200 (push (list var '(selected-frame))
1201 loop-for-bindings)
1202 (push (list temp nil) loop-for-bindings)
1203 (push `(prog1 (not (eq ,var ,temp))
1204 (or ,temp (setq ,temp ,var)))
1205 cl--loop-body)
1206 (push (list var `(next-frame ,var))
1207 loop-for-steps)))
1209 ((memq word '(window windows))
1210 (let ((scr (and (memq (car cl--loop-args) '(in of)) (cl-pop2 cl--loop-args)))
1211 (temp (make-symbol "--cl-var--"))
1212 (minip (make-symbol "--cl-minip--")))
1213 (push (list var (if scr
1214 `(frame-selected-window ,scr)
1215 '(selected-window)))
1216 loop-for-bindings)
1217 ;; If we started in the minibuffer, we need to
1218 ;; ensure that next-window will bring us back there
1219 ;; at some point. (Bug#7492).
1220 ;; (Consider using walk-windows instead of cl-loop if
1221 ;; you care about such things.)
1222 (push (list minip `(minibufferp (window-buffer ,var)))
1223 loop-for-bindings)
1224 (push (list temp nil) loop-for-bindings)
1225 (push `(prog1 (not (eq ,var ,temp))
1226 (or ,temp (setq ,temp ,var)))
1227 cl--loop-body)
1228 (push (list var `(next-window ,var ,minip))
1229 loop-for-steps)))
1232 (let ((handler (and (symbolp word)
1233 (get word 'cl--loop-for-handler))))
1234 (if handler
1235 (funcall handler var)
1236 (error "Expected a `for' preposition, found %s" word)))))
1237 (eq (car cl--loop-args) 'and))
1238 (setq ands t)
1239 (pop cl--loop-args))
1240 (if (and ands loop-for-bindings)
1241 (push (nreverse loop-for-bindings) cl--loop-bindings)
1242 (setq cl--loop-bindings (nconc (mapcar 'list loop-for-bindings)
1243 cl--loop-bindings)))
1244 (if loop-for-sets
1245 (push `(progn
1246 ,(cl--loop-let (nreverse loop-for-sets) 'setq ands)
1247 t) cl--loop-body))
1248 (if loop-for-steps
1249 (push (cons (if ands 'cl-psetq 'setq)
1250 (apply 'append (nreverse loop-for-steps)))
1251 cl--loop-steps))))
1253 ((eq word 'repeat)
1254 (let ((temp (make-symbol "--cl-var--")))
1255 (push (list (list temp (pop cl--loop-args))) cl--loop-bindings)
1256 (push `(>= (setq ,temp (1- ,temp)) 0) cl--loop-body)))
1258 ((memq word '(collect collecting))
1259 (let ((what (pop cl--loop-args))
1260 (var (cl--loop-handle-accum nil 'nreverse)))
1261 (if (eq var cl--loop-accum-var)
1262 (push `(progn (push ,what ,var) t) cl--loop-body)
1263 (push `(progn
1264 (setq ,var (nconc ,var (list ,what)))
1265 t) cl--loop-body))))
1267 ((memq word '(nconc nconcing append appending))
1268 (let ((what (pop cl--loop-args))
1269 (var (cl--loop-handle-accum nil 'nreverse)))
1270 (push `(progn
1271 (setq ,var
1272 ,(if (eq var cl--loop-accum-var)
1273 `(nconc
1274 (,(if (memq word '(nconc nconcing))
1275 #'nreverse #'reverse)
1276 ,what)
1277 ,var)
1278 `(,(if (memq word '(nconc nconcing))
1279 #'nconc #'append)
1280 ,var ,what))) t) cl--loop-body)))
1282 ((memq word '(concat concating))
1283 (let ((what (pop cl--loop-args))
1284 (var (cl--loop-handle-accum "")))
1285 (push `(progn (cl-callf concat ,var ,what) t) cl--loop-body)))
1287 ((memq word '(vconcat vconcating))
1288 (let ((what (pop cl--loop-args))
1289 (var (cl--loop-handle-accum [])))
1290 (push `(progn (cl-callf vconcat ,var ,what) t) cl--loop-body)))
1292 ((memq word '(sum summing))
1293 (let ((what (pop cl--loop-args))
1294 (var (cl--loop-handle-accum 0)))
1295 (push `(progn (cl-incf ,var ,what) t) cl--loop-body)))
1297 ((memq word '(count counting))
1298 (let ((what (pop cl--loop-args))
1299 (var (cl--loop-handle-accum 0)))
1300 (push `(progn (if ,what (cl-incf ,var)) t) cl--loop-body)))
1302 ((memq word '(minimize minimizing maximize maximizing))
1303 (let* ((what (pop cl--loop-args))
1304 (temp (if (cl--simple-expr-p what) what (make-symbol "--cl-var--")))
1305 (var (cl--loop-handle-accum nil))
1306 (func (intern (substring (symbol-name word) 0 3)))
1307 (set `(setq ,var (if ,var (,func ,var ,temp) ,temp))))
1308 (push `(progn ,(if (eq temp what) set
1309 `(let ((,temp ,what)) ,set))
1310 t) cl--loop-body)))
1312 ((eq word 'with)
1313 (let ((bindings nil))
1314 (while (progn (push (list (pop cl--loop-args)
1315 (and (eq (car cl--loop-args) '=) (cl-pop2 cl--loop-args)))
1316 bindings)
1317 (eq (car cl--loop-args) 'and))
1318 (pop cl--loop-args))
1319 (push (nreverse bindings) cl--loop-bindings)))
1321 ((eq word 'while)
1322 (push (pop cl--loop-args) cl--loop-body))
1324 ((eq word 'until)
1325 (push `(not ,(pop cl--loop-args)) cl--loop-body))
1327 ((eq word 'always)
1328 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1329 (push `(setq ,cl--loop-finish-flag ,(pop cl--loop-args)) cl--loop-body)
1330 (setq cl--loop-result t))
1332 ((eq word 'never)
1333 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1334 (push `(setq ,cl--loop-finish-flag (not ,(pop cl--loop-args)))
1335 cl--loop-body)
1336 (setq cl--loop-result t))
1338 ((eq word 'thereis)
1339 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-flag--")))
1340 (or cl--loop-result-var (setq cl--loop-result-var (make-symbol "--cl-var--")))
1341 (push `(setq ,cl--loop-finish-flag
1342 (not (setq ,cl--loop-result-var ,(pop cl--loop-args))))
1343 cl--loop-body))
1345 ((memq word '(if when unless))
1346 (let* ((cond (pop cl--loop-args))
1347 (then (let ((cl--loop-body nil))
1348 (cl-parse-loop-clause)
1349 (cl--loop-build-ands (nreverse cl--loop-body))))
1350 (else (let ((cl--loop-body nil))
1351 (if (eq (car cl--loop-args) 'else)
1352 (progn (pop cl--loop-args) (cl-parse-loop-clause)))
1353 (cl--loop-build-ands (nreverse cl--loop-body))))
1354 (simple (and (eq (car then) t) (eq (car else) t))))
1355 (if (eq (car cl--loop-args) 'end) (pop cl--loop-args))
1356 (if (eq word 'unless) (setq then (prog1 else (setq else then))))
1357 (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
1358 (if simple (nth 1 else) (list (nth 2 else))))))
1359 (if (cl--expr-contains form 'it)
1360 (let ((temp (make-symbol "--cl-var--")))
1361 (push (list temp) cl--loop-bindings)
1362 (setq form `(if (setq ,temp ,cond)
1363 ,@(cl-subst temp 'it form))))
1364 (setq form `(if ,cond ,@form)))
1365 (push (if simple `(progn ,form t) form) cl--loop-body))))
1367 ((memq word '(do doing))
1368 (let ((body nil))
1369 (or (consp (car cl--loop-args)) (error "Syntax error on `do' clause"))
1370 (while (consp (car cl--loop-args)) (push (pop cl--loop-args) body))
1371 (push (cons 'progn (nreverse (cons t body))) cl--loop-body)))
1373 ((eq word 'return)
1374 (or cl--loop-finish-flag (setq cl--loop-finish-flag (make-symbol "--cl-var--")))
1375 (or cl--loop-result-var (setq cl--loop-result-var (make-symbol "--cl-var--")))
1376 (push `(setq ,cl--loop-result-var ,(pop cl--loop-args)
1377 ,cl--loop-finish-flag nil) cl--loop-body))
1380 (let ((handler (and (symbolp word) (get word 'cl--loop-handler))))
1381 (or handler (error "Expected a cl-loop keyword, found %s" word))
1382 (funcall handler))))
1383 (if (eq (car cl--loop-args) 'and)
1384 (progn (pop cl--loop-args) (cl-parse-loop-clause)))))
1386 (defun cl--loop-let (specs body par) ; uses loop-*
1387 (let ((p specs) (temps nil) (new nil))
1388 (while (and p (or (symbolp (car-safe (car p))) (null (cl-cadar p))))
1389 (setq p (cdr p)))
1390 (and par p
1391 (progn
1392 (setq par nil p specs)
1393 (while p
1394 (or (macroexp-const-p (cl-cadar p))
1395 (let ((temp (make-symbol "--cl-var--")))
1396 (push (list temp (cl-cadar p)) temps)
1397 (setcar (cdar p) temp)))
1398 (setq p (cdr p)))))
1399 (while specs
1400 (if (and (consp (car specs)) (listp (caar specs)))
1401 (let* ((spec (caar specs)) (nspecs nil)
1402 (expr (cadr (pop specs)))
1403 (temp (cdr (or (assq spec cl--loop-destr-temps)
1404 (car (push (cons spec (or (last spec 0)
1405 (make-symbol "--cl-var--")))
1406 cl--loop-destr-temps))))))
1407 (push (list temp expr) new)
1408 (while (consp spec)
1409 (push (list (pop spec)
1410 (and expr (list (if spec 'pop 'car) temp)))
1411 nspecs))
1412 (setq specs (nconc (nreverse nspecs) specs)))
1413 (push (pop specs) new)))
1414 (if (eq body 'setq)
1415 (let ((set (cons (if par 'cl-psetq 'setq) (apply 'nconc (nreverse new)))))
1416 (if temps `(let* ,(nreverse temps) ,set) set))
1417 `(,(if par 'let 'let*)
1418 ,(nconc (nreverse temps) (nreverse new)) ,@body))))
1420 (defun cl--loop-handle-accum (def &optional func) ; uses loop-*
1421 (if (eq (car cl--loop-args) 'into)
1422 (let ((var (cl-pop2 cl--loop-args)))
1423 (or (memq var cl--loop-accum-vars)
1424 (progn (push (list (list var def)) cl--loop-bindings)
1425 (push var cl--loop-accum-vars)))
1426 var)
1427 (or cl--loop-accum-var
1428 (progn
1429 (push (list (list (setq cl--loop-accum-var (make-symbol "--cl-var--")) def))
1430 cl--loop-bindings)
1431 (setq cl--loop-result (if func (list func cl--loop-accum-var)
1432 cl--loop-accum-var))
1433 cl--loop-accum-var))))
1435 (defun cl--loop-build-ands (clauses)
1436 (let ((ands nil)
1437 (body nil))
1438 (while clauses
1439 (if (and (eq (car-safe (car clauses)) 'progn)
1440 (eq (car (last (car clauses))) t))
1441 (if (cdr clauses)
1442 (setq clauses (cons (nconc (butlast (car clauses))
1443 (if (eq (car-safe (cadr clauses))
1444 'progn)
1445 (cl-cdadr clauses)
1446 (list (cadr clauses))))
1447 (cddr clauses)))
1448 (setq body (cdr (butlast (pop clauses)))))
1449 (push (pop clauses) ands)))
1450 (setq ands (or (nreverse ands) (list t)))
1451 (list (if (cdr ands) (cons 'and ands) (car ands))
1452 body
1453 (let ((full (if body
1454 (append ands (list (cons 'progn (append body '(t)))))
1455 ands)))
1456 (if (cdr full) (cons 'and full) (car full))))))
1459 ;;; Other iteration control structures.
1461 ;;;###autoload
1462 (defmacro cl-do (steps endtest &rest body)
1463 "The Common Lisp `cl-do' loop.
1465 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1466 (declare (indent 2)
1467 (debug
1468 ((&rest &or symbolp (symbolp &optional form form))
1469 (form body)
1470 cl-declarations body)))
1471 (cl-expand-do-loop steps endtest body nil))
1473 ;;;###autoload
1474 (defmacro cl-do* (steps endtest &rest body)
1475 "The Common Lisp `cl-do*' loop.
1477 \(fn ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
1478 (declare (indent 2) (debug cl-do))
1479 (cl-expand-do-loop steps endtest body t))
1481 (defun cl-expand-do-loop (steps endtest body star)
1482 `(cl-block nil
1483 (,(if star 'let* 'let)
1484 ,(mapcar (lambda (c) (if (consp c) (list (car c) (nth 1 c)) c))
1485 steps)
1486 (while (not ,(car endtest))
1487 ,@body
1488 ,@(let ((sets (mapcar (lambda (c)
1489 (and (consp c) (cdr (cdr c))
1490 (list (car c) (nth 2 c))))
1491 steps)))
1492 (setq sets (delq nil sets))
1493 (and sets
1494 (list (cons (if (or star (not (cdr sets)))
1495 'setq 'cl-psetq)
1496 (apply 'append sets))))))
1497 ,@(or (cdr endtest) '(nil)))))
1499 ;;;###autoload
1500 (defmacro cl-dolist (spec &rest body)
1501 "Loop over a list.
1502 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
1503 Then evaluate RESULT to get return value, default nil.
1504 An implicit nil block is established around the loop.
1506 \(fn (VAR LIST [RESULT]) BODY...)"
1507 (declare (debug ((symbolp form &optional form) cl-declarations body)))
1508 (let ((temp (make-symbol "--cl-dolist-temp--")))
1509 ;; FIXME: Copy&pasted from subr.el.
1510 `(cl-block nil
1511 ;; This is not a reliable test, but it does not matter because both
1512 ;; semantics are acceptable, tho one is slightly faster with dynamic
1513 ;; scoping and the other is slightly faster (and has cleaner semantics)
1514 ;; with lexical scoping.
1515 ,(if lexical-binding
1516 `(let ((,temp ,(nth 1 spec)))
1517 (while ,temp
1518 (let ((,(car spec) (car ,temp)))
1519 ,@body
1520 (setq ,temp (cdr ,temp))))
1521 ,@(if (cdr (cdr spec))
1522 ;; FIXME: This let often leads to "unused var" warnings.
1523 `((let ((,(car spec) nil)) ,@(cdr (cdr spec))))))
1524 `(let ((,temp ,(nth 1 spec))
1525 ,(car spec))
1526 (while ,temp
1527 (setq ,(car spec) (car ,temp))
1528 ,@body
1529 (setq ,temp (cdr ,temp)))
1530 ,@(if (cdr (cdr spec))
1531 `((setq ,(car spec) nil) ,@(cddr spec))))))))
1533 ;;;###autoload
1534 (defmacro cl-dotimes (spec &rest body)
1535 "Loop a certain number of times.
1536 Evaluate BODY with VAR bound to successive integers from 0, inclusive,
1537 to COUNT, exclusive. Then evaluate RESULT to get return value, default
1538 nil.
1540 \(fn (VAR COUNT [RESULT]) BODY...)"
1541 (declare (debug cl-dolist))
1542 (let ((temp (make-symbol "--cl-dotimes-temp--"))
1543 (end (nth 1 spec)))
1544 ;; FIXME: Copy&pasted from subr.el.
1545 `(cl-block nil
1546 ;; This is not a reliable test, but it does not matter because both
1547 ;; semantics are acceptable, tho one is slightly faster with dynamic
1548 ;; scoping and the other has cleaner semantics.
1549 ,(if lexical-binding
1550 (let ((counter '--dotimes-counter--))
1551 `(let ((,temp ,end)
1552 (,counter 0))
1553 (while (< ,counter ,temp)
1554 (let ((,(car spec) ,counter))
1555 ,@body)
1556 (setq ,counter (1+ ,counter)))
1557 ,@(if (cddr spec)
1558 ;; FIXME: This let often leads to "unused var" warnings.
1559 `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
1560 `(let ((,temp ,end)
1561 (,(car spec) 0))
1562 (while (< ,(car spec) ,temp)
1563 ,@body
1564 (cl-incf ,(car spec)))
1565 ,@(cdr (cdr spec)))))))
1567 ;;;###autoload
1568 (defmacro cl-do-symbols (spec &rest body)
1569 "Loop over all symbols.
1570 Evaluate BODY with VAR bound to each interned symbol, or to each symbol
1571 from OBARRAY.
1573 \(fn (VAR [OBARRAY [RESULT]]) BODY...)"
1574 (declare (indent 1)
1575 (debug ((symbolp &optional form form) cl-declarations body)))
1576 ;; Apparently this doesn't have an implicit block.
1577 `(cl-block nil
1578 (let (,(car spec))
1579 (mapatoms #'(lambda (,(car spec)) ,@body)
1580 ,@(and (cadr spec) (list (cadr spec))))
1581 ,(cl-caddr spec))))
1583 ;;;###autoload
1584 (defmacro cl-do-all-symbols (spec &rest body)
1585 (declare (indent 1) (debug ((symbolp &optional form) cl-declarations body)))
1586 `(cl-do-symbols (,(car spec) nil ,(cadr spec)) ,@body))
1589 ;;; Assignments.
1591 ;;;###autoload
1592 (defmacro cl-psetq (&rest args)
1593 "Set SYMs to the values VALs in parallel.
1594 This is like `setq', except that all VAL forms are evaluated (in order)
1595 before assigning any symbols SYM to the corresponding values.
1597 \(fn SYM VAL SYM VAL ...)"
1598 (declare (debug setq))
1599 (cons 'cl-psetf args))
1602 ;;; Binding control structures.
1604 ;;;###autoload
1605 (defmacro cl-progv (symbols values &rest body)
1606 "Bind SYMBOLS to VALUES dynamically in BODY.
1607 The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
1608 Each symbol in the first list is bound to the corresponding value in the
1609 second list (or made unbound if VALUES is shorter than SYMBOLS); then the
1610 BODY forms are executed and their result is returned. This is much like
1611 a `let' form, except that the list of symbols can be computed at run-time."
1612 (declare (indent 2) (debug (form form body)))
1613 `(let ((cl-progv-save nil))
1614 (unwind-protect
1615 (progn (cl-progv-before ,symbols ,values) ,@body)
1616 (cl-progv-after))))
1618 ;;; This should really have some way to shadow 'byte-compile properties, etc.
1619 ;;;###autoload
1620 (defmacro cl-flet (bindings &rest body)
1621 "Make temporary function definitions.
1622 This is an analogue of `let' that operates on the function cell of FUNC
1623 rather than its value cell. The FORMs are evaluated with the specified
1624 function definitions in place, then the definitions are undone (the FUNCs
1625 go back to their previous definitions, or lack thereof).
1627 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1628 (declare (indent 1) (debug ((&rest (cl-defun)) cl-declarations body)))
1629 `(cl-letf* ,(mapcar
1630 (lambda (x)
1631 (if (or (and (fboundp (car x))
1632 (eq (car-safe (symbol-function (car x))) 'macro))
1633 (cdr (assq (car x) cl-macro-environment)))
1634 (error "Use `cl-labels', not `cl-flet', to rebind macro names"))
1635 (let ((func `(cl-function
1636 (lambda ,(cadr x)
1637 (cl-block ,(car x) ,@(cddr x))))))
1638 (when (cl-compiling-file)
1639 ;; Bug#411. It would be nice to fix this.
1640 (and (get (car x) 'byte-compile)
1641 (error "Byte-compiling a redefinition of `%s' \
1642 will not work - use `cl-labels' instead" (symbol-name (car x))))
1643 ;; FIXME This affects the rest of the file, when it
1644 ;; should be restricted to the cl-flet body.
1645 (and (boundp 'byte-compile-function-environment)
1646 (push (cons (car x) (eval func))
1647 byte-compile-function-environment)))
1648 (list `(symbol-function ',(car x)) func)))
1649 bindings)
1650 ,@body))
1652 ;;;###autoload
1653 (defmacro cl-labels (bindings &rest body)
1654 "Make temporary function bindings.
1655 This is like `cl-flet', except the bindings are lexical instead of dynamic.
1656 Unlike `cl-flet', this macro is fully compliant with the Common Lisp standard.
1658 \(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
1659 (declare (indent 1) (debug cl-flet))
1660 (let ((vars nil) (sets nil) (cl-macro-environment cl-macro-environment))
1661 (while bindings
1662 ;; Use `cl-gensym' rather than `make-symbol'. It's important that
1663 ;; (not (eq (symbol-name var1) (symbol-name var2))) because these
1664 ;; vars get added to the cl-macro-environment.
1665 (let ((var (cl-gensym "--cl-var--")))
1666 (push var vars)
1667 (push `(cl-function (lambda . ,(cdar bindings))) sets)
1668 (push var sets)
1669 (push (cons (car (pop bindings))
1670 `(lambda (&rest cl-labels-args)
1671 (cl-list* 'funcall ',var
1672 cl-labels-args)))
1673 cl-macro-environment)))
1674 (cl-macroexpand-all `(cl-lexical-let ,vars (setq ,@sets) ,@body)
1675 cl-macro-environment)))
1677 ;; The following ought to have a better definition for use with newer
1678 ;; byte compilers.
1679 ;;;###autoload
1680 (defmacro cl-macrolet (bindings &rest body)
1681 "Make temporary macro definitions.
1682 This is like `cl-flet', but for macros instead of functions.
1684 \(fn ((NAME ARGLIST BODY...) ...) FORM...)"
1685 (declare (indent 1)
1686 (debug
1687 ((&rest (&define name (&rest arg) cl-declarations-or-string
1688 def-body))
1689 cl-declarations body)))
1690 (if (cdr bindings)
1691 `(cl-macrolet (,(car bindings)) (cl-macrolet ,(cdr bindings) ,@body))
1692 (if (null bindings) (cons 'progn body)
1693 (let* ((name (caar bindings))
1694 (res (cl--transform-lambda (cdar bindings) name)))
1695 (eval (car res))
1696 (cl-macroexpand-all (cons 'progn body)
1697 (cons (cons name `(lambda ,@(cdr res)))
1698 cl-macro-environment))))))
1700 ;;;###autoload
1701 (defmacro cl-symbol-macrolet (bindings &rest body)
1702 "Make symbol macro definitions.
1703 Within the body FORMs, references to the variable NAME will be replaced
1704 by EXPANSION, and (setq NAME ...) will act like (cl-setf EXPANSION ...).
1706 \(fn ((NAME EXPANSION) ...) FORM...)"
1707 (declare (indent 1) (debug ((&rest (symbol sexp)) cl-declarations body)))
1708 (if (cdr bindings)
1709 `(cl-symbol-macrolet (,(car bindings))
1710 (cl-symbol-macrolet ,(cdr bindings) ,@body))
1711 (if (null bindings) (cons 'progn body)
1712 (cl-macroexpand-all (cons 'progn body)
1713 (cons (list (symbol-name (caar bindings))
1714 (cl-cadar bindings))
1715 cl-macro-environment)))))
1717 (defvar cl-closure-vars nil)
1718 ;;;###autoload
1719 (defmacro cl-lexical-let (bindings &rest body)
1720 "Like `let', but lexically scoped.
1721 The main visible difference is that lambdas inside BODY will create
1722 lexical closures as in Common Lisp.
1723 \n(fn BINDINGS BODY)"
1724 (declare (indent 1) (debug let))
1725 (let* ((cl-closure-vars cl-closure-vars)
1726 (vars (mapcar (function
1727 (lambda (x)
1728 (or (consp x) (setq x (list x)))
1729 (push (make-symbol (format "--cl-%s--" (car x)))
1730 cl-closure-vars)
1731 (set (car cl-closure-vars) [bad-lexical-ref])
1732 (list (car x) (cadr x) (car cl-closure-vars))))
1733 bindings))
1734 (ebody
1735 (cl-macroexpand-all
1736 `(cl-symbol-macrolet
1737 ,(mapcar (lambda (x)
1738 `(,(car x) (symbol-value ,(cl-caddr x))))
1739 vars)
1740 ,@body)
1741 cl-macro-environment)))
1742 (if (not (get (car (last cl-closure-vars)) 'used))
1743 ;; Turn (let ((foo (cl-gensym)))
1744 ;; (set foo <val>) ...(symbol-value foo)...)
1745 ;; into (let ((foo <val>)) ...(symbol-value 'foo)...).
1746 ;; This is good because it's more efficient but it only works with
1747 ;; dynamic scoping, since with lexical scoping we'd need
1748 ;; (let ((foo <val>)) ...foo...).
1749 `(progn
1750 ,@(mapcar (lambda (x) `(defvar ,(cl-caddr x))) vars)
1751 (let ,(mapcar (lambda (x) (list (cl-caddr x) (cadr x))) vars)
1752 ,(cl-sublis (mapcar (lambda (x)
1753 (cons (cl-caddr x)
1754 `',(cl-caddr x)))
1755 vars)
1756 ebody)))
1757 `(let ,(mapcar (lambda (x)
1758 (list (cl-caddr x)
1759 `(make-symbol ,(format "--%s--" (car x)))))
1760 vars)
1761 (cl-setf ,@(apply #'append
1762 (mapcar (lambda (x)
1763 (list `(symbol-value ,(cl-caddr x)) (cadr x)))
1764 vars)))
1765 ,ebody))))
1767 ;;;###autoload
1768 (defmacro cl-lexical-let* (bindings &rest body)
1769 "Like `let*', but lexically scoped.
1770 The main visible difference is that lambdas inside BODY, and in
1771 successive bindings within BINDINGS, will create lexical closures
1772 as in Common Lisp. This is similar to the behavior of `let*' in
1773 Common Lisp.
1774 \n(fn BINDINGS BODY)"
1775 (declare (indent 1) (debug let))
1776 (if (null bindings) (cons 'progn body)
1777 (setq bindings (reverse bindings))
1778 (while bindings
1779 (setq body (list `(cl-lexical-let (,(pop bindings)) ,@body))))
1780 (car body)))
1782 ;;; Multiple values.
1784 ;;;###autoload
1785 (defmacro cl-multiple-value-bind (vars form &rest body)
1786 "Collect multiple return values.
1787 FORM must return a list; the BODY is then executed with the first N elements
1788 of this list bound (`let'-style) to each of the symbols SYM in turn. This
1789 is analogous to the Common Lisp `cl-multiple-value-bind' macro, using lists to
1790 simulate true multiple return values. For compatibility, (cl-values A B C) is
1791 a synonym for (list A B C).
1793 \(fn (SYM...) FORM BODY)"
1794 (declare (indent 2) (debug ((&rest symbolp) form body)))
1795 (let ((temp (make-symbol "--cl-var--")) (n -1))
1796 `(let* ((,temp ,form)
1797 ,@(mapcar (lambda (v)
1798 (list v `(nth ,(setq n (1+ n)) ,temp)))
1799 vars))
1800 ,@body)))
1802 ;;;###autoload
1803 (defmacro cl-multiple-value-setq (vars form)
1804 "Collect multiple return values.
1805 FORM must return a list; the first N elements of this list are stored in
1806 each of the symbols SYM in turn. This is analogous to the Common Lisp
1807 `cl-multiple-value-setq' macro, using lists to simulate true multiple return
1808 values. For compatibility, (cl-values A B C) is a synonym for (list A B C).
1810 \(fn (SYM...) FORM)"
1811 (declare (indent 1) (debug ((&rest symbolp) form)))
1812 (cond ((null vars) `(progn ,form nil))
1813 ((null (cdr vars)) `(setq ,(car vars) (car ,form)))
1815 (let* ((temp (make-symbol "--cl-var--")) (n 0))
1816 `(let ((,temp ,form))
1817 (prog1 (setq ,(pop vars) (car ,temp))
1818 (setq ,@(apply #'nconc
1819 (mapcar (lambda (v)
1820 (list v `(nth ,(setq n (1+ n))
1821 ,temp)))
1822 vars)))))))))
1825 ;;; Declarations.
1827 ;;;###autoload
1828 (defmacro cl-locally (&rest body)
1829 (declare (debug t))
1830 (cons 'progn body))
1831 ;;;###autoload
1832 (defmacro cl-the (type form)
1833 (declare (indent 1) (debug (cl-type-spec form)))
1834 form)
1836 (defvar cl-proclaim-history t) ; for future compilers
1837 (defvar cl-declare-stack t) ; for future compilers
1839 (defun cl-do-proclaim (spec hist)
1840 (and hist (listp cl-proclaim-history) (push spec cl-proclaim-history))
1841 (cond ((eq (car-safe spec) 'special)
1842 (if (boundp 'byte-compile-bound-variables)
1843 (setq byte-compile-bound-variables
1844 (append (cdr spec) byte-compile-bound-variables))))
1846 ((eq (car-safe spec) 'inline)
1847 (while (setq spec (cdr spec))
1848 (or (memq (get (car spec) 'byte-optimizer)
1849 '(nil byte-compile-inline-expand))
1850 (error "%s already has a byte-optimizer, can't make it inline"
1851 (car spec)))
1852 (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
1854 ((eq (car-safe spec) 'notinline)
1855 (while (setq spec (cdr spec))
1856 (if (eq (get (car spec) 'byte-optimizer)
1857 'byte-compile-inline-expand)
1858 (put (car spec) 'byte-optimizer nil))))
1860 ((eq (car-safe spec) 'optimize)
1861 (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
1862 '((0 nil) (1 t) (2 t) (3 t))))
1863 (safety (assq (nth 1 (assq 'safety (cdr spec)))
1864 '((0 t) (1 t) (2 t) (3 nil)))))
1865 (if speed (setq cl-optimize-speed (car speed)
1866 byte-optimize (nth 1 speed)))
1867 (if safety (setq cl-optimize-safety (car safety)
1868 byte-compile-delete-errors (nth 1 safety)))))
1870 ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
1871 (while (setq spec (cdr spec))
1872 (if (consp (car spec))
1873 (if (eq (cl-cadar spec) 0)
1874 (byte-compile-disable-warning (caar spec))
1875 (byte-compile-enable-warning (caar spec)))))))
1876 nil)
1878 ;;; Process any proclamations made before cl-macs was loaded.
1879 (defvar cl-proclaims-deferred)
1880 (let ((p (reverse cl-proclaims-deferred)))
1881 (while p (cl-do-proclaim (pop p) t))
1882 (setq cl-proclaims-deferred nil))
1884 ;;;###autoload
1885 (defmacro cl-declare (&rest specs)
1886 "Declare SPECS about the current function while compiling.
1887 For instance
1889 \(cl-declare (warn 0))
1891 will turn off byte-compile warnings in the function.
1892 See Info node `(cl)Declarations' for details."
1893 (if (cl-compiling-file)
1894 (while specs
1895 (if (listp cl-declare-stack) (push (car specs) cl-declare-stack))
1896 (cl-do-proclaim (pop specs) nil)))
1897 nil)
1901 ;;; Generalized variables.
1903 ;;;###autoload
1904 (defmacro cl-define-setf-expander (func args &rest body)
1905 "Define a `cl-setf' method.
1906 This method shows how to handle `cl-setf's to places of the form (NAME ARGS...).
1907 The argument forms ARGS are bound according to ARGLIST, as if NAME were
1908 going to be expanded as a macro, then the BODY forms are executed and must
1909 return a list of five elements: a temporary-variables list, a value-forms
1910 list, a store-variables list (of length one), a store-form, and an access-
1911 form. See `cl-defsetf' for a simpler way to define most setf-methods.
1913 \(fn NAME ARGLIST BODY...)"
1914 (declare (debug
1915 (&define name cl-lambda-list cl-declarations-or-string def-body)))
1916 `(cl-eval-when (compile load eval)
1917 ,@(if (stringp (car body))
1918 (list `(put ',func 'setf-documentation ,(pop body))))
1919 ,(cl--transform-function-property
1920 func 'setf-method (cons args body))))
1922 ;;;###autoload
1923 (defmacro cl-defsetf (func arg1 &rest args)
1924 "Define a `cl-setf' method.
1925 This macro is an easy-to-use substitute for `cl-define-setf-expander' that works
1926 well for simple place forms. In the simple `cl-defsetf' form, `cl-setf's of
1927 the form (cl-setf (NAME ARGS...) VAL) are transformed to function or macro
1928 calls of the form (FUNC ARGS... VAL). Example:
1930 (cl-defsetf aref aset)
1932 Alternate form: (cl-defsetf NAME ARGLIST (STORE) BODY...).
1933 Here, the above `cl-setf' call is expanded by binding the argument forms ARGS
1934 according to ARGLIST, binding the value form VAL to STORE, then executing
1935 BODY, which must return a Lisp form that does the necessary `cl-setf' operation.
1936 Actually, ARGLIST and STORE may be bound to temporary variables which are
1937 introduced automatically to preserve proper execution order of the arguments.
1938 Example:
1940 (cl-defsetf nth (n x) (v) `(setcar (nthcdr ,n ,x) ,v))
1942 \(fn NAME [FUNC | ARGLIST (STORE) BODY...])"
1943 (declare (debug
1944 (&define name
1945 [&or [symbolp &optional stringp]
1946 [cl-lambda-list (symbolp)]]
1947 cl-declarations-or-string def-body)))
1948 (if (and (listp arg1) (consp args))
1949 (let* ((largs nil) (largsr nil)
1950 (temps nil) (tempsr nil)
1951 (restarg nil) (rest-temps nil)
1952 (store-var (car (prog1 (car args) (setq args (cdr args)))))
1953 (store-temp (intern (format "--%s--temp--" store-var)))
1954 (lets1 nil) (lets2 nil)
1955 (docstr nil) (p arg1))
1956 (if (stringp (car args))
1957 (setq docstr (prog1 (car args) (setq args (cdr args)))))
1958 (while (and p (not (eq (car p) '&aux)))
1959 (if (eq (car p) '&rest)
1960 (setq p (cdr p) restarg (car p))
1961 (or (memq (car p) '(&optional &key &allow-other-keys))
1962 (setq largs (cons (if (consp (car p)) (car (car p)) (car p))
1963 largs)
1964 temps (cons (intern (format "--%s--temp--" (car largs)))
1965 temps))))
1966 (setq p (cdr p)))
1967 (setq largs (nreverse largs) temps (nreverse temps))
1968 (if restarg
1969 (setq largsr (append largs (list restarg))
1970 rest-temps (intern (format "--%s--temp--" restarg))
1971 tempsr (append temps (list rest-temps)))
1972 (setq largsr largs tempsr temps))
1973 (let ((p1 largs) (p2 temps))
1974 (while p1
1975 (setq lets1 (cons `(,(car p2)
1976 (make-symbol ,(format "--cl-%s--" (car p1))))
1977 lets1)
1978 lets2 (cons (list (car p1) (car p2)) lets2)
1979 p1 (cdr p1) p2 (cdr p2))))
1980 (if restarg (setq lets2 (cons (list restarg rest-temps) lets2)))
1981 `(cl-define-setf-expander ,func ,arg1
1982 ,@(and docstr (list docstr))
1983 (let*
1984 ,(nreverse
1985 (cons `(,store-temp
1986 (make-symbol ,(format "--cl-%s--" store-var)))
1987 (if restarg
1988 `((,rest-temps
1989 (mapcar (lambda (_) (make-symbol "--cl-var--"))
1990 ,restarg))
1991 ,@lets1)
1992 lets1)))
1993 (list ; 'values
1994 (,(if restarg 'cl-list* 'list) ,@tempsr)
1995 (,(if restarg 'cl-list* 'list) ,@largsr)
1996 (list ,store-temp)
1997 (let*
1998 ,(nreverse
1999 (cons (list store-var store-temp)
2000 lets2))
2001 ,@args)
2002 (,(if restarg 'cl-list* 'list)
2003 ,@(cons `',func tempsr))))))
2004 `(cl-defsetf ,func (&rest args) (store)
2005 ,(let ((call `(cons ',arg1
2006 (append args (list store)))))
2007 (if (car args)
2008 `(list 'progn ,call store)
2009 call)))))
2011 ;;; Some standard place types from Common Lisp.
2012 (cl-defsetf aref aset)
2013 (cl-defsetf car setcar)
2014 (cl-defsetf cdr setcdr)
2015 (cl-defsetf caar (x) (val) `(setcar (car ,x) ,val))
2016 (cl-defsetf cadr (x) (val) `(setcar (cdr ,x) ,val))
2017 (cl-defsetf cdar (x) (val) `(setcdr (car ,x) ,val))
2018 (cl-defsetf cddr (x) (val) `(setcdr (cdr ,x) ,val))
2019 (cl-defsetf elt (seq n) (store)
2020 `(if (listp ,seq) (setcar (nthcdr ,n ,seq) ,store)
2021 (aset ,seq ,n ,store)))
2022 (cl-defsetf get put)
2023 (cl-defsetf cl-get (x y &optional d) (store) `(put ,x ,y ,store))
2024 (cl-defsetf gethash (x h &optional d) (store) `(puthash ,x ,store ,h))
2025 (cl-defsetf nth (n x) (store) `(setcar (nthcdr ,n ,x) ,store))
2026 (cl-defsetf cl-subseq (seq start &optional end) (new)
2027 `(progn (cl-replace ,seq ,new :start1 ,start :end1 ,end) ,new))
2028 (cl-defsetf symbol-function fset)
2029 (cl-defsetf symbol-plist setplist)
2030 (cl-defsetf symbol-value set)
2032 ;;; Various car/cdr aliases. Note that `cadr' is handled specially.
2033 (cl-defsetf cl-first setcar)
2034 (cl-defsetf cl-second (x) (store) `(setcar (cdr ,x) ,store))
2035 (cl-defsetf cl-third (x) (store) `(setcar (cddr ,x) ,store))
2036 (cl-defsetf cl-fourth (x) (store) `(setcar (cl-cdddr ,x) ,store))
2037 (cl-defsetf cl-fifth (x) (store) `(setcar (nthcdr 4 ,x) ,store))
2038 (cl-defsetf cl-sixth (x) (store) `(setcar (nthcdr 5 ,x) ,store))
2039 (cl-defsetf cl-seventh (x) (store) `(setcar (nthcdr 6 ,x) ,store))
2040 (cl-defsetf cl-eighth (x) (store) `(setcar (nthcdr 7 ,x) ,store))
2041 (cl-defsetf cl-ninth (x) (store) `(setcar (nthcdr 8 ,x) ,store))
2042 (cl-defsetf cl-tenth (x) (store) `(setcar (nthcdr 9 ,x) ,store))
2043 (cl-defsetf cl-rest setcdr)
2045 ;;; Some more Emacs-related place types.
2046 (cl-defsetf buffer-file-name set-visited-file-name t)
2047 (cl-defsetf buffer-modified-p (&optional buf) (flag)
2048 `(with-current-buffer ,buf
2049 (set-buffer-modified-p ,flag)))
2050 (cl-defsetf buffer-name rename-buffer t)
2051 (cl-defsetf buffer-string () (store)
2052 `(progn (erase-buffer) (insert ,store)))
2053 (cl-defsetf buffer-substring cl-set-buffer-substring)
2054 (cl-defsetf current-buffer set-buffer)
2055 (cl-defsetf current-case-table set-case-table)
2056 (cl-defsetf current-column move-to-column t)
2057 (cl-defsetf current-global-map use-global-map t)
2058 (cl-defsetf current-input-mode () (store)
2059 `(progn (apply #'set-input-mode ,store) ,store))
2060 (cl-defsetf current-local-map use-local-map t)
2061 (cl-defsetf current-window-configuration set-window-configuration t)
2062 (cl-defsetf default-file-modes set-default-file-modes t)
2063 (cl-defsetf default-value set-default)
2064 (cl-defsetf documentation-property put)
2065 (cl-defsetf face-background (f &optional s) (x) `(set-face-background ,f ,x ,s))
2066 (cl-defsetf face-background-pixmap (f &optional s) (x)
2067 `(set-face-background-pixmap ,f ,x ,s))
2068 (cl-defsetf face-font (f &optional s) (x) `(set-face-font ,f ,x ,s))
2069 (cl-defsetf face-foreground (f &optional s) (x) `(set-face-foreground ,f ,x ,s))
2070 (cl-defsetf face-underline-p (f &optional s) (x)
2071 `(set-face-underline-p ,f ,x ,s))
2072 (cl-defsetf file-modes set-file-modes t)
2073 (cl-defsetf frame-height set-screen-height t)
2074 (cl-defsetf frame-parameters modify-frame-parameters t)
2075 (cl-defsetf frame-visible-p cl-set-frame-visible-p)
2076 (cl-defsetf frame-width set-screen-width t)
2077 (cl-defsetf frame-parameter set-frame-parameter t)
2078 (cl-defsetf terminal-parameter set-terminal-parameter)
2079 (cl-defsetf getenv setenv t)
2080 (cl-defsetf get-register set-register)
2081 (cl-defsetf global-key-binding global-set-key)
2082 (cl-defsetf keymap-parent set-keymap-parent)
2083 (cl-defsetf local-key-binding local-set-key)
2084 (cl-defsetf mark set-mark t)
2085 (cl-defsetf mark-marker set-mark t)
2086 (cl-defsetf marker-position set-marker t)
2087 (cl-defsetf match-data set-match-data t)
2088 (cl-defsetf mouse-position (scr) (store)
2089 `(set-mouse-position ,scr (car ,store) (cadr ,store)
2090 (cddr ,store)))
2091 (cl-defsetf overlay-get overlay-put)
2092 (cl-defsetf overlay-start (ov) (store)
2093 `(progn (move-overlay ,ov ,store (overlay-end ,ov)) ,store))
2094 (cl-defsetf overlay-end (ov) (store)
2095 `(progn (move-overlay ,ov (overlay-start ,ov) ,store) ,store))
2096 (cl-defsetf point goto-char)
2097 (cl-defsetf point-marker goto-char t)
2098 (cl-defsetf point-max () (store)
2099 `(progn (narrow-to-region (point-min) ,store) ,store))
2100 (cl-defsetf point-min () (store)
2101 `(progn (narrow-to-region ,store (point-max)) ,store))
2102 (cl-defsetf process-buffer set-process-buffer)
2103 (cl-defsetf process-filter set-process-filter)
2104 (cl-defsetf process-sentinel set-process-sentinel)
2105 (cl-defsetf process-get process-put)
2106 (cl-defsetf read-mouse-position (scr) (store)
2107 `(set-mouse-position ,scr (car ,store) (cdr ,store)))
2108 (cl-defsetf screen-height set-screen-height t)
2109 (cl-defsetf screen-width set-screen-width t)
2110 (cl-defsetf selected-window select-window)
2111 (cl-defsetf selected-screen select-screen)
2112 (cl-defsetf selected-frame select-frame)
2113 (cl-defsetf standard-case-table set-standard-case-table)
2114 (cl-defsetf syntax-table set-syntax-table)
2115 (cl-defsetf visited-file-modtime set-visited-file-modtime t)
2116 (cl-defsetf window-buffer set-window-buffer t)
2117 (cl-defsetf window-display-table set-window-display-table t)
2118 (cl-defsetf window-dedicated-p set-window-dedicated-p t)
2119 (cl-defsetf window-height () (store)
2120 `(progn (enlarge-window (- ,store (window-height))) ,store))
2121 (cl-defsetf window-hscroll set-window-hscroll)
2122 (cl-defsetf window-parameter set-window-parameter)
2123 (cl-defsetf window-point set-window-point)
2124 (cl-defsetf window-start set-window-start)
2125 (cl-defsetf window-width () (store)
2126 `(progn (enlarge-window (- ,store (window-width)) t) ,store))
2127 (cl-defsetf x-get-secondary-selection x-own-secondary-selection t)
2128 (cl-defsetf x-get-selection x-own-selection t)
2130 ;; This is a hack that allows (cl-setf (eq a 7) B) to mean either
2131 ;; (setq a 7) or (setq a nil) depending on whether B is nil or not.
2132 ;; This is useful when you have control over the PLACE but not over
2133 ;; the VALUE, as is the case in define-minor-mode's :variable.
2134 (cl-define-setf-expander eq (place val)
2135 (let ((method (cl-get-setf-method place cl-macro-environment))
2136 (val-temp (make-symbol "--eq-val--"))
2137 (store-temp (make-symbol "--eq-store--")))
2138 (list (append (nth 0 method) (list val-temp))
2139 (append (nth 1 method) (list val))
2140 (list store-temp)
2141 `(let ((,(car (nth 2 method))
2142 (if ,store-temp ,val-temp (not ,val-temp))))
2143 ,(nth 3 method) ,store-temp)
2144 `(eq ,(nth 4 method) ,val-temp))))
2146 ;;; More complex setf-methods.
2147 ;; These should take &environment arguments, but since full arglists aren't
2148 ;; available while compiling cl-macs, we fake it by referring to the global
2149 ;; variable cl-macro-environment directly.
2151 (cl-define-setf-expander apply (func arg1 &rest rest)
2152 (or (and (memq (car-safe func) '(quote function cl-function))
2153 (symbolp (car-safe (cdr-safe func))))
2154 (error "First arg to apply in cl-setf is not (function SYM): %s" func))
2155 (let* ((form (cons (nth 1 func) (cons arg1 rest)))
2156 (method (cl-get-setf-method form cl-macro-environment)))
2157 (list (car method) (nth 1 method) (nth 2 method)
2158 (cl-setf-make-apply (nth 3 method) (cadr func) (car method))
2159 (cl-setf-make-apply (nth 4 method) (cadr func) (car method)))))
2161 (defun cl-setf-make-apply (form func temps)
2162 (if (eq (car form) 'progn)
2163 `(progn ,(cl-setf-make-apply (cadr form) func temps) ,@(cddr form))
2164 (or (equal (last form) (last temps))
2165 (error "%s is not suitable for use with setf-of-apply" func))
2166 `(apply ',(car form) ,@(cdr form))))
2168 (cl-define-setf-expander nthcdr (n place)
2169 (let ((method (cl-get-setf-method place cl-macro-environment))
2170 (n-temp (make-symbol "--cl-nthcdr-n--"))
2171 (store-temp (make-symbol "--cl-nthcdr-store--")))
2172 (list (cons n-temp (car method))
2173 (cons n (nth 1 method))
2174 (list store-temp)
2175 `(let ((,(car (nth 2 method))
2176 (cl-set-nthcdr ,n-temp ,(nth 4 method)
2177 ,store-temp)))
2178 ,(nth 3 method) ,store-temp)
2179 `(nthcdr ,n-temp ,(nth 4 method)))))
2181 (cl-define-setf-expander cl-getf (place tag &optional def)
2182 (let ((method (cl-get-setf-method place cl-macro-environment))
2183 (tag-temp (make-symbol "--cl-getf-tag--"))
2184 (def-temp (make-symbol "--cl-getf-def--"))
2185 (store-temp (make-symbol "--cl-getf-store--")))
2186 (list (append (car method) (list tag-temp def-temp))
2187 (append (nth 1 method) (list tag def))
2188 (list store-temp)
2189 `(let ((,(car (nth 2 method))
2190 (cl-set-getf ,(nth 4 method) ,tag-temp ,store-temp)))
2191 ,(nth 3 method) ,store-temp)
2192 `(cl-getf ,(nth 4 method) ,tag-temp ,def-temp))))
2194 (cl-define-setf-expander substring (place from &optional to)
2195 (let ((method (cl-get-setf-method place cl-macro-environment))
2196 (from-temp (make-symbol "--cl-substring-from--"))
2197 (to-temp (make-symbol "--cl-substring-to--"))
2198 (store-temp (make-symbol "--cl-substring-store--")))
2199 (list (append (car method) (list from-temp to-temp))
2200 (append (nth 1 method) (list from to))
2201 (list store-temp)
2202 `(let ((,(car (nth 2 method))
2203 (cl-set-substring ,(nth 4 method)
2204 ,from-temp ,to-temp ,store-temp)))
2205 ,(nth 3 method) ,store-temp)
2206 `(substring ,(nth 4 method) ,from-temp ,to-temp))))
2208 ;;; Getting and optimizing setf-methods.
2209 ;;;###autoload
2210 (defun cl-get-setf-method (place &optional env)
2211 "Return a list of five values describing the setf-method for PLACE.
2212 PLACE may be any Lisp form which can appear as the PLACE argument to
2213 a macro like `cl-setf' or `cl-incf'."
2214 (if (symbolp place)
2215 (let ((temp (make-symbol "--cl-setf--")))
2216 (list nil nil (list temp) `(setq ,place ,temp) place))
2217 (or (and (symbolp (car place))
2218 (let* ((func (car place))
2219 (name (symbol-name func))
2220 (method (get func 'setf-method))
2221 (case-fold-search nil))
2222 (or (and method
2223 (let ((cl-macro-environment env))
2224 (setq method (apply method (cdr place))))
2225 (if (and (consp method) (= (length method) 5))
2226 method
2227 (error "Setf-method for %s returns malformed method"
2228 func)))
2229 (and (string-match-p "\\`c[ad][ad][ad]?[ad]?r\\'" name)
2230 (cl-get-setf-method (cl-compiler-macroexpand place)))
2231 (and (eq func 'edebug-after)
2232 (cl-get-setf-method (nth (1- (length place)) place)
2233 env)))))
2234 (if (eq place (setq place (macroexpand place env)))
2235 (if (and (symbolp (car place)) (fboundp (car place))
2236 (symbolp (symbol-function (car place))))
2237 (cl-get-setf-method (cons (symbol-function (car place))
2238 (cdr place)) env)
2239 (error "No setf-method known for %s" (car place)))
2240 (cl-get-setf-method place env)))))
2242 (defun cl-setf-do-modify (place opt-expr)
2243 (let* ((method (cl-get-setf-method place cl-macro-environment))
2244 (temps (car method)) (values (nth 1 method))
2245 (lets nil) (subs nil)
2246 (optimize (and (not (eq opt-expr 'no-opt))
2247 (or (and (not (eq opt-expr 'unsafe))
2248 (cl--safe-expr-p opt-expr))
2249 (cl-setf-simple-store-p (car (nth 2 method))
2250 (nth 3 method)))))
2251 (simple (and optimize (consp place) (cl--simple-exprs-p (cdr place)))))
2252 (while values
2253 (if (or simple (macroexp-const-p (car values)))
2254 (push (cons (pop temps) (pop values)) subs)
2255 (push (list (pop temps) (pop values)) lets)))
2256 (list (nreverse lets)
2257 (cons (car (nth 2 method)) (cl-sublis subs (nth 3 method)))
2258 (cl-sublis subs (nth 4 method)))))
2260 (defun cl-setf-do-store (spec val)
2261 (let ((sym (car spec))
2262 (form (cdr spec)))
2263 (if (or (macroexp-const-p val)
2264 (and (cl--simple-expr-p val) (eq (cl--expr-contains form sym) 1))
2265 (cl-setf-simple-store-p sym form))
2266 (cl-subst val sym form)
2267 `(let ((,sym ,val)) ,form))))
2269 (defun cl-setf-simple-store-p (sym form)
2270 (and (consp form) (eq (cl--expr-contains form sym) 1)
2271 (eq (nth (1- (length form)) form) sym)
2272 (symbolp (car form)) (fboundp (car form))
2273 (not (eq (car-safe (symbol-function (car form))) 'macro))))
2275 ;;; The standard modify macros.
2276 ;;;###autoload
2277 (defmacro cl-setf (&rest args)
2278 "Set each PLACE to the value of its VAL.
2279 This is a generalized version of `setq'; the PLACEs may be symbolic
2280 references such as (car x) or (aref x i), as well as plain symbols.
2281 For example, (cl-setf (cl-cadar x) y) is equivalent to (setcar (cdar x) y).
2282 The return value is the last VAL in the list.
2284 \(fn PLACE VAL PLACE VAL ...)"
2285 (declare (debug (&rest [place form])))
2286 (if (cdr (cdr args))
2287 (let ((sets nil))
2288 (while args (push `(cl-setf ,(pop args) ,(pop args)) sets))
2289 (cons 'progn (nreverse sets)))
2290 (if (symbolp (car args))
2291 (and args (cons 'setq args))
2292 (let* ((method (cl-setf-do-modify (car args) (nth 1 args)))
2293 (store (cl-setf-do-store (nth 1 method) (nth 1 args))))
2294 (if (car method) `(let* ,(car method) ,store) store)))))
2296 ;;;###autoload
2297 (defmacro cl-psetf (&rest args)
2298 "Set PLACEs to the values VALs in parallel.
2299 This is like `cl-setf', except that all VAL forms are evaluated (in order)
2300 before assigning any PLACEs to the corresponding values.
2302 \(fn PLACE VAL PLACE VAL ...)"
2303 (declare (debug cl-setf))
2304 (let ((p args) (simple t) (vars nil))
2305 (while p
2306 (if (or (not (symbolp (car p))) (cl--expr-depends-p (nth 1 p) vars))
2307 (setq simple nil))
2308 (if (memq (car p) vars)
2309 (error "Destination duplicated in psetf: %s" (car p)))
2310 (push (pop p) vars)
2311 (or p (error "Odd number of arguments to cl-psetf"))
2312 (pop p))
2313 (if simple
2314 `(progn (cl-setf ,@args) nil)
2315 (setq args (reverse args))
2316 (let ((expr `(cl-setf ,(cadr args) ,(car args))))
2317 (while (setq args (cddr args))
2318 (setq expr `(cl-setf ,(cadr args) (prog1 ,(car args) ,expr))))
2319 `(progn ,expr nil)))))
2321 ;;;###autoload
2322 (defun cl-do-pop (place)
2323 (if (cl--simple-expr-p place)
2324 `(prog1 (car ,place) (cl-setf ,place (cdr ,place)))
2325 (let* ((method (cl-setf-do-modify place t))
2326 (temp (make-symbol "--cl-pop--")))
2327 `(let* (,@(car method)
2328 (,temp ,(nth 2 method)))
2329 (prog1 (car ,temp)
2330 ,(cl-setf-do-store (nth 1 method) `(cdr ,temp)))))))
2332 ;;;###autoload
2333 (defmacro cl-remf (place tag)
2334 "Remove TAG from property list PLACE.
2335 PLACE may be a symbol, or any generalized variable allowed by `cl-setf'.
2336 The form returns true if TAG was found and removed, nil otherwise."
2337 (declare (debug (place form)))
2338 (let* ((method (cl-setf-do-modify place t))
2339 (tag-temp (and (not (macroexp-const-p tag)) (make-symbol "--cl-remf-tag--")))
2340 (val-temp (and (not (cl--simple-expr-p place))
2341 (make-symbol "--cl-remf-place--")))
2342 (ttag (or tag-temp tag))
2343 (tval (or val-temp (nth 2 method))))
2344 `(let* (,@(car method)
2345 ,@(and val-temp `((,val-temp ,(nth 2 method))))
2346 ,@(and tag-temp `((,tag-temp ,tag))))
2347 (if (eq ,ttag (car ,tval))
2348 (progn ,(cl-setf-do-store (nth 1 method) `(cddr ,tval))
2350 `(cl-do-remf ,tval ,ttag)))))
2352 ;;;###autoload
2353 (defmacro cl-shiftf (place &rest args)
2354 "Shift left among PLACEs.
2355 Example: (cl-shiftf A B C) sets A to B, B to C, and returns the old A.
2356 Each PLACE may be a symbol, or any generalized variable allowed by `cl-setf'.
2358 \(fn PLACE... VAL)"
2359 (declare (debug (&rest place)))
2360 (cond
2361 ((null args) place)
2362 ((symbolp place) `(prog1 ,place (setq ,place (cl-shiftf ,@args))))
2364 (let ((method (cl-setf-do-modify place 'unsafe)))
2365 `(let* ,(car method)
2366 (prog1 ,(nth 2 method)
2367 ,(cl-setf-do-store (nth 1 method) `(cl-shiftf ,@args))))))))
2369 ;;;###autoload
2370 (defmacro cl-rotatef (&rest args)
2371 "Rotate left among PLACEs.
2372 Example: (cl-rotatef A B C) sets A to B, B to C, and C to A. It returns nil.
2373 Each PLACE may be a symbol, or any generalized variable allowed by `cl-setf'.
2375 \(fn PLACE...)"
2376 (declare (debug (&rest place)))
2377 (if (not (memq nil (mapcar 'symbolp args)))
2378 (and (cdr args)
2379 (let ((sets nil)
2380 (first (car args)))
2381 (while (cdr args)
2382 (setq sets (nconc sets (list (pop args) (car args)))))
2383 `(cl-psetf ,@sets ,(car args) ,first)))
2384 (let* ((places (reverse args))
2385 (temp (make-symbol "--cl-rotatef--"))
2386 (form temp))
2387 (while (cdr places)
2388 (let ((method (cl-setf-do-modify (pop places) 'unsafe)))
2389 (setq form `(let* ,(car method)
2390 (prog1 ,(nth 2 method)
2391 ,(cl-setf-do-store (nth 1 method) form))))))
2392 (let ((method (cl-setf-do-modify (car places) 'unsafe)))
2393 `(let* (,@(car method) (,temp ,(nth 2 method)))
2394 ,(cl-setf-do-store (nth 1 method) form) nil)))))
2396 ;;;###autoload
2397 (defmacro cl-letf (bindings &rest body)
2398 "Temporarily bind to PLACEs.
2399 This is the analogue of `let', but with generalized variables (in the
2400 sense of `cl-setf') for the PLACEs. Each PLACE is set to the corresponding
2401 VALUE, then the BODY forms are executed. On exit, either normally or
2402 because of a `throw' or error, the PLACEs are set back to their original
2403 values. Note that this macro is *not* available in Common Lisp.
2404 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2405 the PLACE is not modified before executing BODY.
2407 \(fn ((PLACE VALUE) ...) BODY...)"
2408 (declare (indent 1) (debug ((&rest (gate place &optional form)) body)))
2409 (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
2410 `(let ,bindings ,@body)
2411 (let ((lets nil) (sets nil)
2412 (unsets nil) (rev (reverse bindings)))
2413 (while rev
2414 (let* ((place (if (symbolp (caar rev))
2415 `(symbol-value ',(caar rev))
2416 (caar rev)))
2417 (value (cl-cadar rev))
2418 (method (cl-setf-do-modify place 'no-opt))
2419 (save (make-symbol "--cl-letf-save--"))
2420 (bound (and (memq (car place) '(symbol-value symbol-function))
2421 (make-symbol "--cl-letf-bound--")))
2422 (temp (and (not (macroexp-const-p value)) (cdr bindings)
2423 (make-symbol "--cl-letf-val--"))))
2424 (setq lets (nconc (car method)
2425 (if bound
2426 (list (list bound
2427 (list (if (eq (car place)
2428 'symbol-value)
2429 'boundp 'fboundp)
2430 (nth 1 (nth 2 method))))
2431 (list save `(and ,bound
2432 ,(nth 2 method))))
2433 (list (list save (nth 2 method))))
2434 (and temp (list (list temp value)))
2435 lets)
2436 body (list
2437 `(unwind-protect
2438 (progn
2439 ,@(if (cdr (car rev))
2440 (cons (cl-setf-do-store (nth 1 method)
2441 (or temp value))
2442 body)
2443 body))
2444 ,(if bound
2445 `(if ,bound
2446 ,(cl-setf-do-store (nth 1 method) save)
2447 (,(if (eq (car place) 'symbol-value)
2448 #'makunbound #'fmakunbound)
2449 ,(nth 1 (nth 2 method))))
2450 (cl-setf-do-store (nth 1 method) save))))
2451 rev (cdr rev))))
2452 `(let* ,lets ,@body))))
2455 ;;;###autoload
2456 (defmacro cl-letf* (bindings &rest body)
2457 "Temporarily bind to PLACEs.
2458 This is the analogue of `let*', but with generalized variables (in the
2459 sense of `cl-setf') for the PLACEs. Each PLACE is set to the corresponding
2460 VALUE, then the BODY forms are executed. On exit, either normally or
2461 because of a `throw' or error, the PLACEs are set back to their original
2462 values. Note that this macro is *not* available in Common Lisp.
2463 As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
2464 the PLACE is not modified before executing BODY.
2466 \(fn ((PLACE VALUE) ...) BODY...)"
2467 (declare (indent 1) (debug cl-letf))
2468 (if (null bindings)
2469 (cons 'progn body)
2470 (setq bindings (reverse bindings))
2471 (while bindings
2472 (setq body (list `(cl-letf (,(pop bindings)) ,@body))))
2473 (car body)))
2475 ;;;###autoload
2476 (defmacro cl-callf (func place &rest args)
2477 "Set PLACE to (FUNC PLACE ARGS...).
2478 FUNC should be an unquoted function name. PLACE may be a symbol,
2479 or any generalized variable allowed by `cl-setf'.
2481 \(fn FUNC PLACE ARGS...)"
2482 (declare (indent 2) (debug (cl-function place &rest form)))
2483 (let* ((method (cl-setf-do-modify place (cons 'list args)))
2484 (rargs (cons (nth 2 method) args)))
2485 `(let* ,(car method)
2486 ,(cl-setf-do-store (nth 1 method)
2487 (if (symbolp func) (cons func rargs)
2488 `(funcall #',func ,@rargs))))))
2490 ;;;###autoload
2491 (defmacro cl-callf2 (func arg1 place &rest args)
2492 "Set PLACE to (FUNC ARG1 PLACE ARGS...).
2493 Like `cl-callf', but PLACE is the second argument of FUNC, not the first.
2495 \(fn FUNC ARG1 PLACE ARGS...)"
2496 (declare (indent 3) (debug (cl-function form place &rest form)))
2497 (if (and (cl--safe-expr-p arg1) (cl--simple-expr-p place) (symbolp func))
2498 `(cl-setf ,place (,func ,arg1 ,place ,@args))
2499 (let* ((method (cl-setf-do-modify place (cons 'list args)))
2500 (temp (and (not (macroexp-const-p arg1)) (make-symbol "--cl-arg1--")))
2501 (rargs (cl-list* (or temp arg1) (nth 2 method) args)))
2502 `(let* (,@(and temp (list (list temp arg1))) ,@(car method))
2503 ,(cl-setf-do-store (nth 1 method)
2504 (if (symbolp func) (cons func rargs)
2505 `(funcall #',func ,@rargs)))))))
2507 ;;;###autoload
2508 (defmacro cl-define-modify-macro (name arglist func &optional doc)
2509 "Define a `cl-setf'-like modify macro.
2510 If NAME is called, it combines its PLACE argument with the other arguments
2511 from ARGLIST using FUNC: (cl-define-modify-macro cl-incf (&optional (n 1)) +)"
2512 (declare (debug
2513 (&define name cl-lambda-list ;; should exclude &key
2514 symbolp &optional stringp)))
2515 (if (memq '&key arglist) (error "&key not allowed in cl-define-modify-macro"))
2516 (let ((place (make-symbol "--cl-place--")))
2517 `(cl-defmacro ,name (,place ,@arglist)
2518 ,doc
2519 (,(if (memq '&rest arglist) #'cl-list* #'list)
2520 #'cl-callf ',func ,place
2521 ,@(cl--arglist-args arglist)))))
2524 ;;; Structures.
2526 ;;;###autoload
2527 (defmacro cl-defstruct (struct &rest descs)
2528 "Define a struct type.
2529 This macro defines a new data type called NAME that stores data
2530 in SLOTs. It defines a `make-NAME' constructor, a `copy-NAME'
2531 copier, a `NAME-p' predicate, and slot accessors named `NAME-SLOT'.
2532 You can use the accessors to set the corresponding slots, via `cl-setf'.
2534 NAME may instead take the form (NAME OPTIONS...), where each
2535 OPTION is either a single keyword or (KEYWORD VALUE).
2536 See Info node `(cl)Structures' for a list of valid keywords.
2538 Each SLOT may instead take the form (SLOT SLOT-OPTS...), where
2539 SLOT-OPTS are keyword-value pairs for that slot. Currently, only
2540 one keyword is supported, `:read-only'. If this has a non-nil
2541 value, that slot cannot be set via `cl-setf'.
2543 \(fn NAME SLOTS...)"
2544 (declare (doc-string 2)
2545 (debug
2546 (&define ;Makes top-level form not be wrapped.
2547 [&or symbolp
2548 (gate
2549 symbolp &rest
2550 (&or [":conc-name" symbolp]
2551 [":constructor" symbolp &optional cl-lambda-list]
2552 [":copier" symbolp]
2553 [":predicate" symbolp]
2554 [":include" symbolp &rest sexp] ;; Not finished.
2555 ;; The following are not supported.
2556 ;; [":print-function" ...]
2557 ;; [":type" ...]
2558 ;; [":initial-offset" ...]
2560 [&optional stringp]
2561 ;; All the above is for the following def-form.
2562 &rest &or symbolp (symbolp def-form
2563 &optional ":read-only" sexp))))
2564 (let* ((name (if (consp struct) (car struct) struct))
2565 (opts (cdr-safe struct))
2566 (slots nil)
2567 (defaults nil)
2568 (conc-name (concat (symbol-name name) "-"))
2569 (constructor (intern (format "make-%s" name)))
2570 (constrs nil)
2571 (copier (intern (format "copy-%s" name)))
2572 (predicate (intern (format "%s-p" name)))
2573 (print-func nil) (print-auto nil)
2574 (safety (if (cl-compiling-file) cl-optimize-safety 3))
2575 (include nil)
2576 (tag (intern (format "cl-struct-%s" name)))
2577 (tag-symbol (intern (format "cl-struct-%s-tags" name)))
2578 (include-descs nil)
2579 (side-eff nil)
2580 (type nil)
2581 (named nil)
2582 (forms nil)
2583 pred-form pred-check)
2584 (if (stringp (car descs))
2585 (push `(put ',name 'structure-documentation
2586 ,(pop descs)) forms))
2587 (setq descs (cons '(cl-tag-slot)
2588 (mapcar (function (lambda (x) (if (consp x) x (list x))))
2589 descs)))
2590 (while opts
2591 (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
2592 (args (cdr-safe (pop opts))))
2593 (cond ((eq opt :conc-name)
2594 (if args
2595 (setq conc-name (if (car args)
2596 (symbol-name (car args)) ""))))
2597 ((eq opt :constructor)
2598 (if (cdr args)
2599 (progn
2600 ;; If this defines a constructor of the same name as
2601 ;; the default one, don't define the default.
2602 (if (eq (car args) constructor)
2603 (setq constructor nil))
2604 (push args constrs))
2605 (if args (setq constructor (car args)))))
2606 ((eq opt :copier)
2607 (if args (setq copier (car args))))
2608 ((eq opt :predicate)
2609 (if args (setq predicate (car args))))
2610 ((eq opt :include)
2611 (setq include (car args)
2612 include-descs (mapcar (function
2613 (lambda (x)
2614 (if (consp x) x (list x))))
2615 (cdr args))))
2616 ((eq opt :print-function)
2617 (setq print-func (car args)))
2618 ((eq opt :type)
2619 (setq type (car args)))
2620 ((eq opt :named)
2621 (setq named t))
2622 ((eq opt :initial-offset)
2623 (setq descs (nconc (make-list (car args) '(cl-skip-slot))
2624 descs)))
2626 (error "Slot option %s unrecognized" opt)))))
2627 (if print-func
2628 (setq print-func
2629 `(progn (funcall #',print-func cl-x cl-s cl-n) t))
2630 (or type (and include (not (get include 'cl-struct-print)))
2631 (setq print-auto t
2632 print-func (and (or (not (or include type)) (null print-func))
2633 `(progn
2634 (princ ,(format "#S(%s" name) cl-s))))))
2635 (if include
2636 (let ((inc-type (get include 'cl-struct-type))
2637 (old-descs (get include 'cl-struct-slots)))
2638 (or inc-type (error "%s is not a struct name" include))
2639 (and type (not (eq (car inc-type) type))
2640 (error ":type disagrees with :include for %s" name))
2641 (while include-descs
2642 (setcar (memq (or (assq (caar include-descs) old-descs)
2643 (error "No slot %s in included struct %s"
2644 (caar include-descs) include))
2645 old-descs)
2646 (pop include-descs)))
2647 (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
2648 type (car inc-type)
2649 named (assq 'cl-tag-slot descs))
2650 (if (cadr inc-type) (setq tag name named t))
2651 (let ((incl include))
2652 (while incl
2653 (push `(cl-pushnew ',tag
2654 ,(intern (format "cl-struct-%s-tags" incl)))
2655 forms)
2656 (setq incl (get incl 'cl-struct-include)))))
2657 (if type
2658 (progn
2659 (or (memq type '(vector list))
2660 (error "Invalid :type specifier: %s" type))
2661 (if named (setq tag name)))
2662 (setq type 'vector named 'true)))
2663 (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
2664 (push `(defvar ,tag-symbol) forms)
2665 (setq pred-form (and named
2666 (let ((pos (- (length descs)
2667 (length (memq (assq 'cl-tag-slot descs)
2668 descs)))))
2669 (if (eq type 'vector)
2670 `(and (vectorp cl-x)
2671 (>= (length cl-x) ,(length descs))
2672 (memq (aref cl-x ,pos) ,tag-symbol))
2673 (if (= pos 0)
2674 `(memq (car-safe cl-x) ,tag-symbol)
2675 `(and (consp cl-x)
2676 (memq (nth ,pos cl-x) ,tag-symbol))))))
2677 pred-check (and pred-form (> safety 0)
2678 (if (and (eq (cl-caadr pred-form) 'vectorp)
2679 (= safety 1))
2680 (cons 'and (cl-cdddr pred-form)) pred-form)))
2681 (let ((pos 0) (descp descs))
2682 (while descp
2683 (let* ((desc (pop descp))
2684 (slot (car desc)))
2685 (if (memq slot '(cl-tag-slot cl-skip-slot))
2686 (progn
2687 (push nil slots)
2688 (push (and (eq slot 'cl-tag-slot) `',tag)
2689 defaults))
2690 (if (assq slot descp)
2691 (error "Duplicate slots named %s in %s" slot name))
2692 (let ((accessor (intern (format "%s%s" conc-name slot))))
2693 (push slot slots)
2694 (push (nth 1 desc) defaults)
2695 (push (cl-list*
2696 'cl-defsubst accessor '(cl-x)
2697 (append
2698 (and pred-check
2699 (list `(or ,pred-check
2700 (error "%s accessing a non-%s"
2701 ',accessor ',name))))
2702 (list (if (eq type 'vector) `(aref cl-x ,pos)
2703 (if (= pos 0) '(car cl-x)
2704 `(nth ,pos cl-x)))))) forms)
2705 (push (cons accessor t) side-eff)
2706 (push `(cl-define-setf-expander ,accessor (cl-x)
2707 ,(if (cadr (memq :read-only (cddr desc)))
2708 `(progn (ignore cl-x)
2709 (error "%s is a read-only slot"
2710 ',accessor))
2711 ;; If cl is loaded only for compilation,
2712 ;; the call to cl-struct-setf-expander would
2713 ;; cause a warning because it may not be
2714 ;; defined at run time. Suppress that warning.
2715 `(progn
2716 (declare-function
2717 cl-struct-setf-expander "cl-macs"
2718 (x name accessor pred-form pos))
2719 (cl-struct-setf-expander
2720 cl-x ',name ',accessor
2721 ,(and pred-check `',pred-check)
2722 ,pos))))
2723 forms)
2724 (if print-auto
2725 (nconc print-func
2726 (list `(princ ,(format " %s" slot) cl-s)
2727 `(prin1 (,accessor cl-x) cl-s)))))))
2728 (setq pos (1+ pos))))
2729 (setq slots (nreverse slots)
2730 defaults (nreverse defaults))
2731 (and predicate pred-form
2732 (progn (push `(cl-defsubst ,predicate (cl-x)
2733 ,(if (eq (car pred-form) 'and)
2734 (append pred-form '(t))
2735 `(and ,pred-form t))) forms)
2736 (push (cons predicate 'error-free) side-eff)))
2737 (and copier
2738 (progn (push `(defun ,copier (x) (copy-sequence x)) forms)
2739 (push (cons copier t) side-eff)))
2740 (if constructor
2741 (push (list constructor
2742 (cons '&key (delq nil (copy-sequence slots))))
2743 constrs))
2744 (while constrs
2745 (let* ((name (caar constrs))
2746 (args (cadr (pop constrs)))
2747 (anames (cl--arglist-args args))
2748 (make (cl-mapcar (function (lambda (s d) (if (memq s anames) s d)))
2749 slots defaults)))
2750 (push `(cl-defsubst ,name
2751 (&cl-defs '(nil ,@descs) ,@args)
2752 (,type ,@make)) forms)
2753 (if (cl--safe-expr-p `(progn ,@(mapcar #'cl-second descs)))
2754 (push (cons name t) side-eff))))
2755 (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
2756 (if print-func
2757 (push `(push
2758 ;; The auto-generated function does not pay attention to
2759 ;; the depth argument cl-n.
2760 (lambda (cl-x cl-s ,(if print-auto '_cl-n 'cl-n))
2761 (and ,pred-form ,print-func))
2762 cl-custom-print-functions)
2763 forms))
2764 (push `(setq ,tag-symbol (list ',tag)) forms)
2765 (push `(cl-eval-when (compile load eval)
2766 (put ',name 'cl-struct-slots ',descs)
2767 (put ',name 'cl-struct-type ',(list type (eq named t)))
2768 (put ',name 'cl-struct-include ',include)
2769 (put ',name 'cl-struct-print ,print-auto)
2770 ,@(mapcar (lambda (x)
2771 `(put ',(car x) 'side-effect-free ',(cdr x)))
2772 side-eff))
2773 forms)
2774 `(progn ,@(nreverse (cons `',name forms)))))
2776 ;;;###autoload
2777 (defun cl-struct-setf-expander (x name accessor pred-form pos)
2778 (let* ((temp (make-symbol "--cl-x--")) (store (make-symbol "--cl-store--")))
2779 (list (list temp) (list x) (list store)
2780 `(progn
2781 ,@(and pred-form
2782 (list `(or ,(cl-subst temp 'cl-x pred-form)
2783 (error ,(format
2784 "%s storing a non-%s"
2785 accessor name)))))
2786 ,(if (eq (car (get name 'cl-struct-type)) 'vector)
2787 `(aset ,temp ,pos ,store)
2788 `(setcar
2789 ,(if (<= pos 5)
2790 (let ((xx temp))
2791 (while (>= (setq pos (1- pos)) 0)
2792 (setq xx `(cdr ,xx)))
2794 `(nthcdr ,pos ,temp))
2795 ,store)))
2796 (list accessor temp))))
2799 ;;; Types and assertions.
2801 ;;;###autoload
2802 (defmacro cl-deftype (name arglist &rest body)
2803 "Define NAME as a new data type.
2804 The type name can then be used in `cl-typecase', `cl-check-type', etc."
2805 (declare (debug cl-defmacro) (doc-string 3))
2806 `(cl-eval-when (compile load eval)
2807 ,(cl--transform-function-property
2808 name 'cl-deftype-handler (cons `(&cl-defs '('*) ,@arglist) body))))
2810 (defun cl--make-type-test (val type)
2811 (if (symbolp type)
2812 (cond ((get type 'cl-deftype-handler)
2813 (cl--make-type-test val (funcall (get type 'cl-deftype-handler))))
2814 ((memq type '(nil t)) type)
2815 ((eq type 'null) `(null ,val))
2816 ((eq type 'atom) `(atom ,val))
2817 ((eq type 'float) `(cl-floatp-safe ,val))
2818 ((eq type 'real) `(numberp ,val))
2819 ((eq type 'fixnum) `(integerp ,val))
2820 ;; FIXME: Should `character' accept things like ?\C-\M-a ? --Stef
2821 ((memq type '(character string-char)) `(characterp ,val))
2823 (let* ((name (symbol-name type))
2824 (namep (intern (concat name "p"))))
2825 (if (fboundp namep) (list namep val)
2826 (list (intern (concat name "-p")) val)))))
2827 (cond ((get (car type) 'cl-deftype-handler)
2828 (cl--make-type-test val (apply (get (car type) 'cl-deftype-handler)
2829 (cdr type))))
2830 ((memq (car type) '(integer float real number))
2831 (delq t `(and ,(cl--make-type-test val (car type))
2832 ,(if (memq (cadr type) '(* nil)) t
2833 (if (consp (cadr type)) `(> ,val ,(cl-caadr type))
2834 `(>= ,val ,(cadr type))))
2835 ,(if (memq (cl-caddr type) '(* nil)) t
2836 (if (consp (cl-caddr type)) `(< ,val ,(cl-caaddr type))
2837 `(<= ,val ,(cl-caddr type)))))))
2838 ((memq (car type) '(and or not))
2839 (cons (car type)
2840 (mapcar (function (lambda (x) (cl--make-type-test val x)))
2841 (cdr type))))
2842 ((memq (car type) '(member cl-member))
2843 `(and (cl-member ,val ',(cdr type)) t))
2844 ((eq (car type) 'satisfies) (list (cadr type) val))
2845 (t (error "Bad type spec: %s" type)))))
2847 ;;;###autoload
2848 (defun cl-typep (object type) ; See compiler macro below.
2849 "Check that OBJECT is of type TYPE.
2850 TYPE is a Common Lisp-style type specifier."
2851 (eval (cl--make-type-test 'object type)))
2853 ;;;###autoload
2854 (defmacro cl-check-type (form type &optional string)
2855 "Verify that FORM is of type TYPE; signal an error if not.
2856 STRING is an optional description of the desired type."
2857 (declare (debug (place cl-type-spec &optional stringp)))
2858 (and (or (not (cl-compiling-file))
2859 (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2860 (let* ((temp (if (cl--simple-expr-p form 3)
2861 form (make-symbol "--cl-var--")))
2862 (body `(or ,(cl--make-type-test temp type)
2863 (signal 'wrong-type-argument
2864 (list ,(or string `',type)
2865 ,temp ',form)))))
2866 (if (eq temp form) `(progn ,body nil)
2867 `(let ((,temp ,form)) ,body nil)))))
2869 ;;;###autoload
2870 (defmacro cl-assert (form &optional show-args string &rest args)
2871 "Verify that FORM returns non-nil; signal an error if not.
2872 Second arg SHOW-ARGS means to include arguments of FORM in message.
2873 Other args STRING and ARGS... are arguments to be passed to `error'.
2874 They are not evaluated unless the assertion fails. If STRING is
2875 omitted, a default message listing FORM itself is used."
2876 (declare (debug (form &rest form)))
2877 (and (or (not (cl-compiling-file))
2878 (< cl-optimize-speed 3) (= cl-optimize-safety 3))
2879 (let ((sargs (and show-args
2880 (delq nil (mapcar (lambda (x)
2881 (unless (macroexp-const-p x)
2883 (cdr form))))))
2884 `(progn
2885 (or ,form
2886 ,(if string
2887 `(error ,string ,@sargs ,@args)
2888 `(signal 'cl-assertion-failed
2889 (list ',form ,@sargs))))
2890 nil))))
2892 ;;; Compiler macros.
2894 ;;;###autoload
2895 (defmacro cl-define-compiler-macro (func args &rest body)
2896 "Define a compiler-only macro.
2897 This is like `defmacro', but macro expansion occurs only if the call to
2898 FUNC is compiled (i.e., not interpreted). Compiler macros should be used
2899 for optimizing the way calls to FUNC are compiled; the form returned by
2900 BODY should do the same thing as a call to the normal function called
2901 FUNC, though possibly more efficiently. Note that, like regular macros,
2902 compiler macros are expanded repeatedly until no further expansions are
2903 possible. Unlike regular macros, BODY can decide to \"punt\" and leave the
2904 original function call alone by declaring an initial `&whole foo' parameter
2905 and then returning foo."
2906 (declare (debug cl-defmacro))
2907 (let ((p args) (res nil))
2908 (while (consp p) (push (pop p) res))
2909 (setq args (nconc (nreverse res) (and p (list '&rest p)))))
2910 `(cl-eval-when (compile load eval)
2911 ,(cl--transform-function-property
2912 func 'compiler-macro
2913 (cons (if (memq '&whole args) (delq '&whole args)
2914 (cons '_cl-whole-arg args)) body))
2915 ;; This is so that describe-function can locate
2916 ;; the macro definition.
2917 (let ((file ,(or buffer-file-name
2918 (and (boundp 'byte-compile-current-file)
2919 (stringp byte-compile-current-file)
2920 byte-compile-current-file))))
2921 (if file (put ',func 'compiler-macro-file
2922 (purecopy (file-name-nondirectory file)))))))
2924 ;;;###autoload
2925 (defun cl-compiler-macroexpand (form)
2926 (while
2927 (let ((func (car-safe form)) (handler nil))
2928 (while (and (symbolp func)
2929 (not (setq handler (get func 'compiler-macro)))
2930 (fboundp func)
2931 (or (not (eq (car-safe (symbol-function func)) 'autoload))
2932 (load (nth 1 (symbol-function func)))))
2933 (setq func (symbol-function func)))
2934 (and handler
2935 (not (eq form (setq form (apply handler form (cdr form))))))))
2936 form)
2938 ;; Optimize away unused block-wrappers.
2940 (defvar cl--active-block-names nil)
2942 (cl-define-compiler-macro cl-block-wrapper (cl-form)
2943 (let* ((cl-entry (cons (nth 1 (nth 1 cl-form)) nil))
2944 (cl--active-block-names (cons cl-entry cl--active-block-names))
2945 (cl-body (macroexpand-all ;Performs compiler-macro expansions.
2946 (cons 'progn (cddr cl-form))
2947 macroexpand-all-environment)))
2948 ;; FIXME: To avoid re-applying macroexpand-all, we'd like to be able
2949 ;; to indicate that this return value is already fully expanded.
2950 (if (cdr cl-entry)
2951 `(catch ,(nth 1 cl-form) ,@(cdr cl-body))
2952 cl-body)))
2954 (cl-define-compiler-macro cl-block-throw (cl-tag cl-value)
2955 (let ((cl-found (assq (nth 1 cl-tag) cl--active-block-names)))
2956 (if cl-found (setcdr cl-found t)))
2957 `(throw ,cl-tag ,cl-value))
2959 ;;;###autoload
2960 (defmacro cl-defsubst (name args &rest body)
2961 "Define NAME as a function.
2962 Like `defun', except the function is automatically declared `inline',
2963 ARGLIST allows full Common Lisp conventions, and BODY is implicitly
2964 surrounded by (cl-block NAME ...).
2966 \(fn NAME ARGLIST [DOCSTRING] BODY...)"
2967 (declare (debug cl-defun))
2968 (let* ((argns (cl--arglist-args args)) (p argns)
2969 (pbody (cons 'progn body))
2970 (unsafe (not (cl--safe-expr-p pbody))))
2971 (while (and p (eq (cl--expr-contains args (car p)) 1)) (pop p))
2972 `(progn
2973 ,(if p nil ; give up if defaults refer to earlier args
2974 `(cl-define-compiler-macro ,name
2975 ,(if (memq '&key args)
2976 `(&whole cl-whole &cl-quote ,@args)
2977 (cons '&cl-quote args))
2978 (cl-defsubst-expand
2979 ',argns '(cl-block ,name ,@body)
2980 ;; We used to pass `simple' as
2981 ;; (not (or unsafe (cl-expr-access-order pbody argns)))
2982 ;; But this is much too simplistic since it
2983 ;; does not pay attention to the argvs (and
2984 ;; cl-expr-access-order itself is also too naive).
2986 ,(and (memq '&key args) 'cl-whole) ,unsafe ,@argns)))
2987 (cl-defun ,name ,args ,@body))))
2989 (defun cl-defsubst-expand (argns body simple whole unsafe &rest argvs)
2990 (if (and whole (not (cl--safe-expr-p (cons 'progn argvs)))) whole
2991 (if (cl--simple-exprs-p argvs) (setq simple t))
2992 (let* ((substs ())
2993 (lets (delq nil
2994 (cl-mapcar (lambda (argn argv)
2995 (if (or simple (macroexp-const-p argv))
2996 (progn (push (cons argn argv) substs)
2997 (and unsafe (list argn argv)))
2998 (list argn argv)))
2999 argns argvs))))
3000 ;; FIXME: `sublis/subst' will happily substitute the symbol
3001 ;; `argn' in places where it's not used as a reference
3002 ;; to a variable.
3003 ;; FIXME: `sublis/subst' will happily copy `argv' to a different
3004 ;; scope, leading to name capture.
3005 (setq body (cond ((null substs) body)
3006 ((null (cdr substs))
3007 (cl-subst (cdar substs) (caar substs) body))
3008 (t (cl-sublis substs body))))
3009 (if lets `(let ,lets ,body) body))))
3012 ;; Compile-time optimizations for some functions defined in this package.
3013 ;; Note that cl.el arranges to force cl-macs to be loaded at compile-time,
3014 ;; mainly to make sure these macros will be present.
3016 (put 'eql 'byte-compile nil)
3017 (cl-define-compiler-macro eql (&whole form a b)
3018 (cond ((macroexp-const-p a)
3019 (let ((val (cl--const-expr-val a)))
3020 (if (and (numberp val) (not (integerp val)))
3021 `(equal ,a ,b)
3022 `(eq ,a ,b))))
3023 ((macroexp-const-p b)
3024 (let ((val (cl--const-expr-val b)))
3025 (if (and (numberp val) (not (integerp val)))
3026 `(equal ,a ,b)
3027 `(eq ,a ,b))))
3028 ((cl--simple-expr-p a 5)
3029 `(if (numberp ,a)
3030 (equal ,a ,b)
3031 (eq ,a ,b)))
3032 ((and (cl--safe-expr-p a)
3033 (cl--simple-expr-p b 5))
3034 `(if (numberp ,b)
3035 (equal ,a ,b)
3036 (eq ,a ,b)))
3037 (t form)))
3039 (cl-define-compiler-macro cl-member (&whole form a list &rest keys)
3040 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3041 (cl--const-expr-val (nth 1 keys)))))
3042 (cond ((eq test 'eq) `(memq ,a ,list))
3043 ((eq test 'equal) `(member ,a ,list))
3044 ((or (null keys) (eq test 'eql)) `(memql ,a ,list))
3045 (t form))))
3047 (cl-define-compiler-macro cl-assoc (&whole form a list &rest keys)
3048 (let ((test (and (= (length keys) 2) (eq (car keys) :test)
3049 (cl--const-expr-val (nth 1 keys)))))
3050 (cond ((eq test 'eq) `(assq ,a ,list))
3051 ((eq test 'equal) `(assoc ,a ,list))
3052 ((and (macroexp-const-p a) (or (null keys) (eq test 'eql)))
3053 (if (cl-floatp-safe (cl--const-expr-val a))
3054 `(assoc ,a ,list) `(assq ,a ,list)))
3055 (t form))))
3057 (cl-define-compiler-macro cl-adjoin (&whole form a list &rest keys)
3058 (if (and (cl--simple-expr-p a) (cl--simple-expr-p list)
3059 (not (memq :key keys)))
3060 `(if (cl-member ,a ,list ,@keys) ,list (cons ,a ,list))
3061 form))
3063 (cl-define-compiler-macro cl-list* (arg &rest others)
3064 (let* ((args (reverse (cons arg others)))
3065 (form (car args)))
3066 (while (setq args (cdr args))
3067 (setq form `(cons ,(car args) ,form)))
3068 form))
3070 (cl-define-compiler-macro cl-get (sym prop &optional def)
3071 (if def
3072 `(cl-getf (symbol-plist ,sym) ,prop ,def)
3073 `(get ,sym ,prop)))
3075 (cl-define-compiler-macro cl-typep (&whole form val type)
3076 (if (macroexp-const-p type)
3077 (let ((res (cl--make-type-test val (cl--const-expr-val type))))
3078 (if (or (memq (cl--expr-contains res val) '(nil 1))
3079 (cl--simple-expr-p val)) res
3080 (let ((temp (make-symbol "--cl-var--")))
3081 `(let ((,temp ,val)) ,(cl-subst temp val res)))))
3082 form))
3085 (mapc (lambda (y)
3086 (put (car y) 'side-effect-free t)
3087 (put (car y) 'compiler-macro
3088 `(lambda (_w x)
3089 ,(if (symbolp (cadr y))
3090 `(list ',(cadr y)
3091 (list ',(cl-caddr y) x))
3092 (cons 'list (cdr y))))))
3093 '((cl-first 'car x) (cl-second 'cadr x) (cl-third 'cl-caddr x) (cl-fourth 'cl-cadddr x)
3094 (cl-fifth 'nth 4 x) (cl-sixth 'nth 5 x) (cl-seventh 'nth 6 x)
3095 (cl-eighth 'nth 7 x) (cl-ninth 'nth 8 x) (cl-tenth 'nth 9 x)
3096 (cl-rest 'cdr x) (cl-endp 'null x) (cl-plusp '> x 0) (cl-minusp '< x 0)
3097 (cl-caaar car caar) (cl-caadr car cadr) (cl-cadar car cdar)
3098 (cl-caddr car cddr) (cl-cdaar cdr caar) (cl-cdadr cdr cadr)
3099 (cl-cddar cdr cdar) (cl-cdddr cdr cddr) (cl-caaaar car cl-caaar)
3100 (cl-caaadr car cl-caadr) (cl-caadar car cl-cadar) (cl-caaddr car cl-caddr)
3101 (cl-cadaar car cl-cdaar) (cl-cadadr car cl-cdadr) (cl-caddar car cl-cddar)
3102 (cl-cadddr car cl-cdddr) (cl-cdaaar cdr cl-caaar) (cl-cdaadr cdr cl-caadr)
3103 (cl-cdadar cdr cl-cadar) (cl-cdaddr cdr cl-caddr) (cl-cddaar cdr cl-cdaar)
3104 (cl-cddadr cdr cl-cdadr) (cl-cdddar cdr cl-cddar) (cl-cddddr cdr cl-cdddr) ))
3106 ;;; Things that are inline.
3107 (cl-proclaim '(inline cl-floatp-safe cl-acons cl-map cl-concatenate cl-notany cl-notevery
3108 cl-set-elt cl-revappend cl-nreconc gethash))
3110 ;;; Things that are side-effect-free.
3111 (mapc (lambda (x) (put x 'side-effect-free t))
3112 '(cl-oddp cl-evenp cl-signum last butlast cl-ldiff cl-pairlis cl-gcd cl-lcm
3113 cl-isqrt cl-floor cl-ceiling cl-truncate cl-round cl-mod cl-rem cl-subseq
3114 cl-list-length cl-get cl-getf))
3116 ;;; Things that are side-effect-and-error-free.
3117 (mapc (lambda (x) (put x 'side-effect-free 'error-free))
3118 '(eql cl-floatp-safe cl-list* cl-subst cl-acons cl-equalp cl-random-state-p
3119 copy-tree cl-sublis))
3122 (run-hooks 'cl-macs-load-hook)
3124 ;; Local variables:
3125 ;; byte-compile-dynamic: t
3126 ;; byte-compile-warnings: (not cl-functions)
3127 ;; generated-autoload-file: "cl-loaddefs.el"
3128 ;; End:
3130 ;;; cl-macs.el ends here