cl-macs.el 103 KB
Newer Older
1
;;; cl-macs.el --- Common Lisp macros  -*- lexical-binding: t; coding: utf-8 -*-
Richard M. Stallman's avatar
Richard M. Stallman committed
2

3
;; Copyright (C) 1993, 2001-2012  Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4 5 6 7

;; Author: Dave Gillespie <daveg@synaptics.com>
;; Version: 2.02
;; Keywords: extensions
8
;; Package: emacs
Richard M. Stallman's avatar
Richard M. Stallman committed
9 10 11

;; This file is part of GNU Emacs.

12
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
13
;; it under the terms of the GNU General Public License as published by
14 15
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
16 17 18 19 20 21 22

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; 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/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
24

Richard M. Stallman's avatar
Richard M. Stallman committed
25
;;; Commentary:
Richard M. Stallman's avatar
Richard M. Stallman committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

;; These are extensions to Emacs Lisp that provide a degree of
;; Common Lisp compatibility, beyond what is already built-in
;; in Emacs Lisp.
;;
;; This package was written by Dave Gillespie; it is a complete
;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
;;
;; Bug reports, comments, and suggestions are welcome!

;; This file contains the portions of the Common Lisp extensions
;; package which should be autoloaded, but need only be present
;; if the compiler or interpreter is used---this file is not
;; necessary for executing compiled code.

;; See cl.el for Change Log.


Richard M. Stallman's avatar
Richard M. Stallman committed
44
;;; Code:
Richard M. Stallman's avatar
Richard M. Stallman committed
45

46
(require 'cl-lib)
47
(require 'macroexp)
48 49
;; `gv' is required here because cl-macs can be loaded before loaddefs.el.
(require 'gv)
Richard M. Stallman's avatar
Richard M. Stallman committed
50 51

(defmacro cl-pop2 (place)
52
  (declare (debug edebug-sexps))
53 54
  `(prog1 (car (cdr ,place))
     (setq ,place (cdr (cdr ,place)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
55 56 57 58 59 60

(defvar cl-optimize-safety)
(defvar cl-optimize-speed)

;;; Initialization.

61 62 63
;;; Some predicates for analyzing Lisp forms.
;; These are used by various
;; macro expanders to optimize the results in certain common cases.
Richard M. Stallman's avatar
Richard M. Stallman committed
64

65
(defconst cl--simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
66
			    car-safe cdr-safe progn prog1 prog2))
67
(defconst cl--safe-funcs '(* / % length memq list vector vectorp
68 69
			  < > <= >= = error))

70 71
(defun cl--simple-expr-p (x &optional size)
  "Check if no side effects, and executes quickly."
72
  (or size (setq size 10))
73
  (if (and (consp x) (not (memq (car x) '(quote function cl-function))))
74
      (and (symbolp (car x))
75
	   (or (memq (car x) cl--simple-funcs)
76 77 78 79
	       (get (car x) 'side-effect-free))
	   (progn
	     (setq size (1- size))
	     (while (and (setq x (cdr x))
80
			 (setq size (cl--simple-expr-p (car x) size))))
81 82 83
	     (and (null x) (>= size 0) size)))
    (and (> size 0) (1- size))))

84 85
(defun cl--simple-exprs-p (xs)
  (while (and xs (cl--simple-expr-p (car xs)))
86 87 88
    (setq xs (cdr xs)))
  (not xs))

89 90
(defun cl--safe-expr-p (x)
  "Check if no side effects."
91
  (or (not (and (consp x) (not (memq (car x) '(quote function cl-function)))))
92
      (and (symbolp (car x))
93 94
	   (or (memq (car x) cl--simple-funcs)
	       (memq (car x) cl--safe-funcs)
95 96
	       (get (car x) 'side-effect-free))
	   (progn
97
	     (while (and (setq x (cdr x)) (cl--safe-expr-p (car x))))
98 99 100
	     (null x)))))

;;; Check if constant (i.e., no side effects or dependencies).
101
(defun cl--const-expr-p (x)
102 103
  (cond ((consp x)
	 (or (eq (car x) 'quote)
104
	     (and (memq (car x) '(function cl-function))
105 106 107 108 109
		  (or (symbolp (nth 1 x))
		      (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
	((symbolp x) (and (memq x '(nil t)) t))
	(t t)))

110 111
(defun cl--const-expr-val (x)
  (and (macroexp-const-p x) (if (consp x) (nth 1 x) x)))
112 113

(defun cl-expr-access-order (x v)
114 115 116 117 118 119
  ;; This apparently tries to return nil iff the expression X evaluates
  ;; the variables V in the same order as they appear in V (so as to
  ;; be able to replace those vars with the expressions they're bound
  ;; to).
  ;; FIXME: This is very naive, it doesn't even check to see if those
  ;; variables appear more than once.
120
  (if (macroexp-const-p x) v
121 122 123 124 125 126
    (if (consp x)
	(progn
	  (while (setq x (cdr x)) (setq v (cl-expr-access-order (car x) v)))
	  v)
      (if (eq x (car v)) (cdr v) '(t)))))

127 128
(defun cl--expr-contains (x y)
  "Count number of times X refers to Y.  Return nil for 0 times."
129
  ;; FIXME: This is naive, and it will cl-count Y as referred twice in
130 131 132
  ;; (let ((Y 1)) Y) even though it should be 0.  Also it is often called on
  ;; non-macroexpanded code, so it may also miss some occurrences that would
  ;; only appear in the expanded code.
133
  (cond ((equal y x) 1)
134
	((and (consp x) (not (memq (car x) '(quote function cl-function))))
135
	 (let ((sum 0))
136
	   (while (consp x)
137 138
	     (setq sum (+ sum (or (cl--expr-contains (pop x) y) 0))))
	   (setq sum (+ sum (or (cl--expr-contains x y) 0)))
139 140 141
	   (and (> sum 0) sum)))
	(t nil)))

142 143
(defun cl--expr-contains-any (x y)
  (while (and y (not (cl--expr-contains x (car y)))) (pop y))
144 145
  y)

146 147 148 149
(defun cl--expr-depends-p (x y)
  "Check whether X may depend on any of the symbols in Y."
  (and (not (macroexp-const-p x))
       (or (not (cl--safe-expr-p x)) (cl--expr-contains-any x y))))
150

Richard M. Stallman's avatar
Richard M. Stallman committed
151 152
;;; Symbols.

153
(defvar cl--gensym-counter)
154
;;;###autoload
155
(defun cl-gensym (&optional prefix)
Richard M. Stallman's avatar
Richard M. Stallman committed
156 157
  "Generate a new uninterned symbol.
The name is made by appending a number to PREFIX, default \"G\"."
158 159
  (let ((pfix (if (stringp prefix) prefix "G"))
	(num (if (integerp prefix) prefix
160 161
	       (prog1 cl--gensym-counter
		 (setq cl--gensym-counter (1+ cl--gensym-counter))))))
162
    (make-symbol (format "%s%d" pfix num))))
Richard M. Stallman's avatar
Richard M. Stallman committed
163

164
;;;###autoload
165
(defun cl-gentemp (&optional prefix)
Richard M. Stallman's avatar
Richard M. Stallman committed
166 167
  "Generate a new interned symbol with a unique name.
The name is made by appending a number to PREFIX, default \"G\"."
168
  (let ((pfix (if (stringp prefix) prefix "G"))
Richard M. Stallman's avatar
Richard M. Stallman committed
169
	name)
170 171
    (while (intern-soft (setq name (format "%s%d" pfix cl--gensym-counter)))
      (setq cl--gensym-counter (1+ cl--gensym-counter)))
Richard M. Stallman's avatar
Richard M. Stallman committed
172 173 174 175 176
    (intern name)))


;;; Program structure.

177
(def-edebug-spec cl-declarations
178
  (&rest ("cl-declare" &rest sexp)))
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

(def-edebug-spec cl-declarations-or-string
  (&or stringp cl-declarations))

(def-edebug-spec cl-lambda-list
  (([&rest arg]
    [&optional ["&optional" cl-&optional-arg &rest cl-&optional-arg]]
    [&optional ["&rest" arg]]
    [&optional ["&key" [cl-&key-arg &rest cl-&key-arg]
		&optional "&allow-other-keys"]]
    [&optional ["&aux" &rest
		&or (symbolp &optional def-form) symbolp]]
    )))

(def-edebug-spec cl-&optional-arg
  (&or (arg &optional def-form arg) arg))

(def-edebug-spec cl-&key-arg
  (&or ([&or (symbolp arg) arg] &optional def-form arg) arg))

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
(defconst cl--lambda-list-keywords
  '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))

(defvar cl--bind-block) (defvar cl--bind-defs) (defvar cl--bind-enquote)
(defvar cl--bind-inits) (defvar cl--bind-lets) (defvar cl--bind-forms)

(defun cl--transform-lambda (form bind-block)
  (let* ((args (car form)) (body (cdr form)) (orig-args args)
	 (cl--bind-block bind-block) (cl--bind-defs nil) (cl--bind-enquote nil)
	 (cl--bind-inits nil) (cl--bind-lets nil) (cl--bind-forms nil)
	 (header nil) (simple-args nil))
    (while (or (stringp (car body))
	       (memq (car-safe (car body)) '(interactive cl-declare)))
      (push (pop body) header))
    (setq args (if (listp args) (cl-copy-list args) (list '&rest args)))
    (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
    (if (setq cl--bind-defs (cadr (memq '&cl-defs args)))
	(setq args (delq '&cl-defs (delq cl--bind-defs args))
	      cl--bind-defs (cadr cl--bind-defs)))
    (if (setq cl--bind-enquote (memq '&cl-quote args))
	(setq args (delq '&cl-quote args)))
    (if (memq '&whole args) (error "&whole not currently implemented"))
    (let* ((p (memq '&environment args)) (v (cadr p))
           (env-exp 'macroexpand-all-environment))
      (if p (setq args (nconc (delq (car p) (delq v args))
                              (list '&aux (list v env-exp))))))
    (while (and args (symbolp (car args))
		(not (memq (car args) '(nil &rest &body &key &aux)))
		(not (and (eq (car args) '&optional)
			  (or cl--bind-defs (consp (cadr args))))))
      (push (pop args) simple-args))
    (or (eq cl--bind-block 'cl-none)
	(setq body (list `(cl-block ,cl--bind-block ,@body))))
    (if (null args)
	(cl-list* nil (nreverse simple-args) (nconc (nreverse header) body))
      (if (memq '&optional simple-args) (push '&optional args))
      (cl--do-arglist args nil (- (length simple-args)
                                  (if (memq '&optional simple-args) 1 0)))
      (setq cl--bind-lets (nreverse cl--bind-lets))
      (cl-list* (and cl--bind-inits `(cl-eval-when (compile load eval)
                                ,@(nreverse cl--bind-inits)))
	     (nconc (nreverse simple-args)
		    (list '&rest (car (pop cl--bind-lets))))
	     (nconc (let ((hdr (nreverse header)))
                      ;; Macro expansion can take place in the middle of
                      ;; apparently harmless computation, so it should not
                      ;; touch the match-data.
                      (save-match-data
                        (require 'help-fns)
                        (cons (help-add-fundoc-usage
                               (if (stringp (car hdr)) (pop hdr))
                               (format "%S"
                                       (cons 'fn
                                             (cl--make-usage-args orig-args))))
                              hdr)))
		    (list `(let* ,cl--bind-lets
                             ,@(nreverse cl--bind-forms)
                             ,@body)))))))

258
;;;###autoload
259
(defmacro cl-defun (name args &rest body)
260
  "Define NAME as a function.
Richard M. Stallman's avatar
Richard M. Stallman committed
261
Like normal `defun', except ARGLIST allows full Common Lisp conventions,
262
and BODY is implicitly surrounded by (cl-block NAME ...).
263 264

\(fn NAME ARGLIST [DOCSTRING] BODY...)"
265 266
  (declare (debug
            ;; Same as defun but use cl-lambda-list.
267
            (&define [&or name ("setf" :name setf name)]
268 269 270
                     cl-lambda-list
                     cl-declarations-or-string
                     [&optional ("interactive" interactive)]
271
                     def-body))
272
           (doc-string 3)
273
           (indent 2))
274
  (let* ((res (cl--transform-lambda (cons args body) name))
275 276
	 (form `(defun ,name ,@(cdr res))))
    (if (car res) `(progn ,(car res) ,form) form)))
Richard M. Stallman's avatar
Richard M. Stallman committed
277

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
;; The lambda list for macros is different from that of normal lambdas.
;; Note that &environment is only allowed as first or last items in the
;; top level list.

(def-edebug-spec cl-macro-list
  (([&optional "&environment" arg]
    [&rest cl-macro-arg]
    [&optional ["&optional" &rest
		&or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
    [&optional [[&or "&rest" "&body"] cl-macro-arg]]
    [&optional ["&key" [&rest
			[&or ([&or (symbolp cl-macro-arg) arg]
			      &optional def-form cl-macro-arg)
			     arg]]
		&optional "&allow-other-keys"]]
    [&optional ["&aux" &rest
		&or (symbolp &optional def-form) symbolp]]
    [&optional "&environment" arg]
    )))

(def-edebug-spec cl-macro-arg
  (&or arg cl-macro-list1))

(def-edebug-spec cl-macro-list1
  (([&optional "&whole" arg]  ;; only allowed at lower levels
    [&rest cl-macro-arg]
    [&optional ["&optional" &rest
		&or (cl-macro-arg &optional def-form cl-macro-arg) arg]]
    [&optional [[&or "&rest" "&body"] cl-macro-arg]]
    [&optional ["&key" [&rest
			[&or ([&or (symbolp cl-macro-arg) arg]
			      &optional def-form cl-macro-arg)
			     arg]]
		&optional "&allow-other-keys"]]
    [&optional ["&aux" &rest
		&or (symbolp &optional def-form) symbolp]]
    . [&or arg nil])))

316
;;;###autoload
317
(defmacro cl-defmacro (name args &rest body)
318
  "Define NAME as a macro.
Richard M. Stallman's avatar
Richard M. Stallman committed
319
Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
320
and BODY is implicitly surrounded by (cl-block NAME ...).
321 322

\(fn NAME ARGLIST [DOCSTRING] BODY...)"
323
  (declare (debug
324
            (&define name cl-macro-list cl-declarations-or-string def-body))
325
           (doc-string 3)
326
           (indent 2))
327
  (let* ((res (cl--transform-lambda (cons args body) name))
328 329
	 (form `(defmacro ,name ,@(cdr res))))
    (if (car res) `(progn ,(car res) ,form) form)))
Richard M. Stallman's avatar
Richard M. Stallman committed
330

331 332 333 334 335 336
(def-edebug-spec cl-lambda-expr
  (&define ("lambda" cl-lambda-list
	    ;;cl-declarations-or-string
	    ;;[&optional ("interactive" interactive)]
	    def-body)))

337
;; Redefine function-form to also match cl-function
338 339 340 341
(def-edebug-spec function-form
  ;; form at the end could also handle "function",
  ;; but recognize it specially to avoid wrapping function forms.
  (&or ([&or "quote" "function"] &or symbolp lambda-expr)
342
       ("cl-function" cl-function)
343 344
       form))

345
;;;###autoload
346
(defmacro cl-function (func)
347
  "Introduce a function.
348 349
Like normal `function', except that if argument is a lambda form,
its argument list allows full Common Lisp conventions."
350
  (declare (debug (&or symbolp cl-lambda-expr)))
Richard M. Stallman's avatar
Richard M. Stallman committed
351
  (if (eq (car-safe func) 'lambda)
352
      (let* ((res (cl--transform-lambda (cdr func) 'cl-none))
353 354 355
	     (form `(function (lambda . ,(cdr res)))))
	(if (car res) `(progn ,(car res) ,form) form))
    `(function ,func)))
Richard M. Stallman's avatar
Richard M. Stallman committed
356

357 358
(declare-function help-add-fundoc-usage "help-fns" (docstring arglist))

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
(defun cl--make-usage-var (x)
  "X can be a var or a (destructuring) lambda-list."
  (cond
   ((symbolp x) (make-symbol (upcase (symbol-name x))))
   ((consp x) (cl--make-usage-args x))
   (t x)))

(defun cl--make-usage-args (arglist)
  ;; `orig-args' can contain &cl-defs (an internal
  ;; CL thingy I don't understand), so remove it.
  (let ((x (memq '&cl-defs arglist)))
    (when x (setq arglist (delq (car x) (remq (cadr x) arglist)))))
  (let ((state nil))
    (mapcar (lambda (x)
              (cond
               ((symbolp x)
                (if (eq ?\& (aref (symbol-name x) 0))
                    (setq state x)
                  (make-symbol (upcase (symbol-name x)))))
               ((not (consp x)) x)
               ((memq state '(nil &rest)) (cl--make-usage-args x))
               (t        ;(VAR INITFORM SVAR) or ((KEYWORD VAR) INITFORM SVAR).
381
                (cl-list*
382 383 384 385 386 387 388 389
                 (if (and (consp (car x)) (eq state '&key))
                     (list (caar x) (cl--make-usage-var (nth 1 (car x))))
                   (cl--make-usage-var (car x)))
                 (nth 1 x)                          ;INITFORM.
                 (cl--make-usage-args (nthcdr 2 x)) ;SVAR.
                 ))))
            arglist)))

390
(defun cl--do-arglist (args expr &optional num)   ; uses bind-*
Richard M. Stallman's avatar
Richard M. Stallman committed
391
  (if (nlistp args)
392
      (if (or (memq args cl--lambda-list-keywords) (not (symbolp args)))
Richard M. Stallman's avatar
Richard M. Stallman committed
393
	  (error "Invalid argument name: %s" args)
394
	(push (list args expr) cl--bind-lets))
395
    (setq args (cl-copy-list args))
Richard M. Stallman's avatar
Richard M. Stallman committed
396 397 398 399 400
    (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
    (let ((p (memq '&body args))) (if p (setcar p '&rest)))
    (if (memq '&environment args) (error "&environment used incorrectly"))
    (let ((save-args args)
	  (restarg (memq '&rest args))
401
	  (safety (if (cl--compiling-file) cl-optimize-safety 3))
Richard M. Stallman's avatar
Richard M. Stallman committed
402 403 404 405
	  (keys nil)
	  (laterarg nil) (exactarg nil) minarg)
      (or num (setq num 0))
      (if (listp (cadr restarg))
406
	  (setq restarg (make-symbol "--cl-rest--"))
Richard M. Stallman's avatar
Richard M. Stallman committed
407
	(setq restarg (cadr restarg)))
408
      (push (list restarg expr) cl--bind-lets)
Richard M. Stallman's avatar
Richard M. Stallman committed
409
      (if (eq (car args) '&whole)
410
	  (push (list (cl-pop2 args) restarg) cl--bind-lets))
Richard M. Stallman's avatar
Richard M. Stallman committed
411 412
      (let ((p args))
	(setq minarg restarg)
413
	(while (and p (not (memq (car p) cl--lambda-list-keywords)))
Richard M. Stallman's avatar
Richard M. Stallman committed
414 415 416
	  (or (eq p args) (setq minarg (list 'cdr minarg)))
	  (setq p (cdr p)))
	(if (memq (car p) '(nil &aux))
417
	    (setq minarg `(= (length ,restarg)
418
                             ,(length (cl-ldiff args p)))
Richard M. Stallman's avatar
Richard M. Stallman committed
419
		  exactarg (not (eq args p)))))
420
      (while (and args (not (memq (car args) cl--lambda-list-keywords)))
Richard M. Stallman's avatar
Richard M. Stallman committed
421 422
	(let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
			    restarg)))
423
	  (cl--do-arglist
424
	   (pop args)
Richard M. Stallman's avatar
Richard M. Stallman committed
425
	   (if (or laterarg (= safety 0)) poparg
426 427
	     `(if ,minarg ,poparg
                (signal 'wrong-number-of-arguments
428 429
                        (list ,(and (not (eq cl--bind-block 'cl-none))
                                    `',cl--bind-block)
430
                              (length ,restarg)))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
431
	(setq num (1+ num) laterarg t))
432
      (while (and (eq (car args) '&optional) (pop args))
433
	(while (and args (not (memq (car args) cl--lambda-list-keywords)))
434
	  (let ((arg (pop args)))
Richard M. Stallman's avatar
Richard M. Stallman committed
435
	    (or (consp arg) (setq arg (list arg)))
436
	    (if (cddr arg) (cl--do-arglist (nth 2 arg) `(and ,restarg t)))
Richard M. Stallman's avatar
Richard M. Stallman committed
437
	    (let ((def (if (cdr arg) (nth 1 arg)
438 439
			 (or (car cl--bind-defs)
			     (nth 1 (assq (car arg) cl--bind-defs)))))
440
		  (poparg `(pop ,restarg)))
441
	      (and def cl--bind-enquote (setq def `',def))
442
	      (cl--do-arglist (car arg)
443
			     (if def `(if ,restarg ,poparg ,def) poparg))
Richard M. Stallman's avatar
Richard M. Stallman committed
444 445 446
	      (setq num (1+ num))))))
      (if (eq (car args) '&rest)
	  (let ((arg (cl-pop2 args)))
447
	    (if (consp arg) (cl--do-arglist arg restarg)))
Richard M. Stallman's avatar
Richard M. Stallman committed
448
	(or (eq (car args) '&key) (= safety 0) exactarg
449 450 451
	    (push `(if ,restarg
                       (signal 'wrong-number-of-arguments
                               (list
452 453
                                ,(and (not (eq cl--bind-block 'cl-none))
                                      `',cl--bind-block)
454
                                (+ ,num (length ,restarg)))))
455
                  cl--bind-forms)))
456
      (while (and (eq (car args) '&key) (pop args))
457
	(while (and args (not (memq (car args) cl--lambda-list-keywords)))
458
	  (let ((arg (pop args)))
459
	    (or (consp arg) (setq arg (list arg)))
Richard M. Stallman's avatar
Richard M. Stallman committed
460 461
	    (let* ((karg (if (consp (car arg)) (caar arg)
			   (intern (format ":%s" (car arg)))))
462
		   (varg (if (consp (car arg)) (cl-cadar arg) (car arg)))
Richard M. Stallman's avatar
Richard M. Stallman committed
463
		   (def (if (cdr arg) (cadr arg)
464
			  (or (car cl--bind-defs) (cadr (assq varg cl--bind-defs)))))
465
		   (look `(memq ',karg ,restarg)))
466
	      (and def cl--bind-enquote (setq def `',def))
Richard M. Stallman's avatar
Richard M. Stallman committed
467
	      (if (cddr arg)
468
		  (let* ((temp (or (nth 2 arg) (make-symbol "--cl-var--")))
469
			 (val `(car (cdr ,temp))))
470 471
		    (cl--do-arglist temp look)
		    (cl--do-arglist varg
472 473 474
				   `(if ,temp
                                        (prog1 ,val (setq ,temp t))
                                      ,def)))
475
		(cl--do-arglist
Richard M. Stallman's avatar
Richard M. Stallman committed
476
		 varg
477
		 `(car (cdr ,(if (null def)
Richard M. Stallman's avatar
Richard M. Stallman committed
478
				 look
479
			       `(or ,look
480 481
                                    ,(if (eq (cl--const-expr-p def) t)
					 `'(nil ,(cl--const-expr-val def))
482
				       `(list nil ,def))))))))
483
	      (push karg keys)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
484
      (setq keys (nreverse keys))
485
      (or (and (eq (car args) '&allow-other-keys) (pop args))
Richard M. Stallman's avatar
Richard M. Stallman committed
486
	  (null keys) (= safety 0)
487
	  (let* ((var (make-symbol "--cl-keys--"))
Richard M. Stallman's avatar
Richard M. Stallman committed
488
		 (allow '(:allow-other-keys))
489 490 491 492 493 494 495 496 497 498 499
		 (check `(while ,var
                           (cond
                            ((memq (car ,var) ',(append keys allow))
                             (setq ,var (cdr (cdr ,var))))
                            ((car (cdr (memq (quote ,@allow) ,restarg)))
                             (setq ,var nil))
                            (t
                             (error
                              ,(format "Keyword argument %%s not one of %s"
                                       keys)
                              (car ,var)))))))
500
	    (push `(let ((,var ,restarg)) ,check) cl--bind-forms)))
501
      (while (and (eq (car args) '&aux) (pop args))
502
	(while (and args (not (memq (car args) cl--lambda-list-keywords)))
Richard M. Stallman's avatar
Richard M. Stallman committed
503
	  (if (consp (car args))
504
	      (if (and cl--bind-enquote (cl-cadar args))
505
		  (cl--do-arglist (caar args)
506
				 `',(cadr (pop args)))
507 508
		(cl--do-arglist (caar args) (cadr (pop args))))
	    (cl--do-arglist (pop args) nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
509 510
      (if args (error "Malformed argument list %s" save-args)))))

511
(defun cl--arglist-args (args)
Richard M. Stallman's avatar
Richard M. Stallman committed
512 513 514
  (if (nlistp args) (list args)
    (let ((res nil) (kind nil) arg)
      (while (consp args)
515
	(setq arg (pop args))
516
	(if (memq arg cl--lambda-list-keywords) (setq kind arg)
517
	  (if (eq arg '&cl-defs) (pop args)
Richard M. Stallman's avatar
Richard M. Stallman committed
518 519
	    (and (consp arg) kind (setq arg (car arg)))
	    (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
520
	    (setq res (nconc res (cl--arglist-args arg))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
521 522
      (nconc res (and args (list args))))))

523
;;;###autoload
524
(defmacro cl-destructuring-bind (args expr &rest body)
525 526
  (declare (indent 2)
           (debug (&define cl-macro-list def-form cl-declarations def-body)))
527 528
  (let* ((cl--bind-lets nil) (cl--bind-forms nil) (cl--bind-inits nil)
	 (cl--bind-defs nil) (cl--bind-block 'cl-none) (cl--bind-enquote nil))
529
    (cl--do-arglist (or args '(&aux)) expr)
530 531 532
    (append '(progn) cl--bind-inits
	    (list `(let* ,(nreverse cl--bind-lets)
                     ,@(nreverse cl--bind-forms) ,@body)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
533 534


535
;;; The `cl-eval-when' form.
Richard M. Stallman's avatar
Richard M. Stallman committed
536 537 538

(defvar cl-not-toplevel nil)

539
;;;###autoload
540
(defmacro cl-eval-when (when &rest body)
541
  "Control when BODY is evaluated.
Richard M. Stallman's avatar
Richard M. Stallman committed
542 543
If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
544 545 546
If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level.

\(fn (WHEN...) BODY...)"
547
  (declare (indent 1) (debug ((&rest &or "compile" "load" "eval") body)))
548
  (if (and (fboundp 'cl--compiling-file) (cl--compiling-file)
Richard M. Stallman's avatar
Richard M. Stallman committed
549
	   (not cl-not-toplevel) (not (boundp 'for-effect)))  ; horrible kludge
550
      (let ((comp (or (memq 'compile when) (memq :compile-toplevel when)))
Richard M. Stallman's avatar
Richard M. Stallman committed
551
	    (cl-not-toplevel t))
552
	(if (or (memq 'load when) (memq :load-toplevel when))
553
	    (if comp (cons 'progn (mapcar 'cl--compile-time-too body))
554
	      `(if nil nil ,@body))
Richard M. Stallman's avatar
Richard M. Stallman committed
555
	  (progn (if comp (eval (cons 'progn body))) nil)))
556
    (and (or (memq 'eval when) (memq :execute when))
Richard M. Stallman's avatar
Richard M. Stallman committed
557 558
	 (cons 'progn body))))

559
(defun cl--compile-time-too (form)
Richard M. Stallman's avatar
Richard M. Stallman committed
560 561
  (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
      (setq form (macroexpand
562
		  form (cons '(cl-eval-when) byte-compile-macro-environment))))
Richard M. Stallman's avatar
Richard M. Stallman committed
563
  (cond ((eq (car-safe form) 'progn)
564
	 (cons 'progn (mapcar 'cl--compile-time-too (cdr form))))
565
	((eq (car-safe form) 'cl-eval-when)
Richard M. Stallman's avatar
Richard M. Stallman committed
566
	 (let ((when (nth 1 form)))
567
	   (if (or (memq 'eval when) (memq :execute when))
568
	       `(cl-eval-when (compile ,@when) ,@(cddr form))
Richard M. Stallman's avatar
Richard M. Stallman committed
569 570 571
	     form)))
	(t (eval form) form)))

572
;;;###autoload
573
(defmacro cl-load-time-value (form &optional _read-only)
Richard M. Stallman's avatar
Richard M. Stallman committed
574 575
  "Like `progn', but evaluates the body at load time.
The result of the body appears to the compiler as a quoted constant."
576
  (declare (debug (form &optional sexp)))
577
  (if (cl--compiling-file)
578
      (let* ((temp (cl-gentemp "--cl-load-time--"))
579
	     (set `(set ',temp ,form)))
Richard M. Stallman's avatar
Richard M. Stallman committed
580 581 582
	(if (and (fboundp 'byte-compile-file-form-defmumble)
		 (boundp 'this-kind) (boundp 'that-one))
	    (fset 'byte-compile-file-form
583 584 585 586 587
		  `(lambda (form)
                     (fset 'byte-compile-file-form
                           ',(symbol-function 'byte-compile-file-form))
                     (byte-compile-file-form ',set)
                     (byte-compile-file-form form)))
588
	  (print set (symbol-value 'byte-compile--outbuffer)))
589 590
	`(symbol-value ',temp))
    `',(eval form)))
Richard M. Stallman's avatar
Richard M. Stallman committed
591 592 593 594


;;; Conditional control structures.

595
;;;###autoload
596
(defmacro cl-case (expr &rest clauses)
597
  "Eval EXPR and choose among clauses on that value.
Richard M. Stallman's avatar
Richard M. Stallman committed
598 599
Each clause looks like (KEYLIST BODY...).  EXPR is evaluated and compared
against each key in each KEYLIST; the corresponding BODY is evaluated.
600
If no clause succeeds, cl-case returns nil.  A single atom may be used in
601
place of a KEYLIST of one atom.  A KEYLIST of t or `otherwise' is
Richard M. Stallman's avatar
Richard M. Stallman committed
602
allowed only in the final clause, and matches if no other keys match.
603 604
Key values are compared by `eql'.
\n(fn EXPR (KEYLIST BODY...)...)"
605
  (declare (indent 1) (debug (form &rest (sexp body))))
606
  (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
Richard M. Stallman's avatar
Richard M. Stallman committed
607 608 609 610 611 612 613
	 (head-list nil)
	 (body (cons
		'cond
		(mapcar
		 (function
		  (lambda (c)
		    (cons (cond ((memq (car c) '(t otherwise)) t)
614 615
				((eq (car c) 'cl--ecase-error-flag)
				 `(error "cl-ecase failed: %s, %s"
616
                                         ,temp ',(reverse head-list)))
Richard M. Stallman's avatar
Richard M. Stallman committed
617 618
				((listp (car c))
				 (setq head-list (append (car c) head-list))
619
				 `(cl-member ,temp ',(car c)))
Richard M. Stallman's avatar
Richard M. Stallman committed
620 621 622 623
				(t
				 (if (memq (car c) head-list)
				     (error "Duplicate key in case: %s"
					    (car c)))
624
				 (push (car c) head-list)
625
				 `(eql ,temp ',(car c))))
Richard M. Stallman's avatar
Richard M. Stallman committed
626 627 628
			  (or (cdr c) '(nil)))))
		 clauses))))
    (if (eq temp expr) body
629
      `(let ((,temp ,expr)) ,body))))
Richard M. Stallman's avatar
Richard M. Stallman committed
630

631
;;;###autoload
632 633
(defmacro cl-ecase (expr &rest clauses)
  "Like `cl-case', but error if no cl-case fits.
634 635
`otherwise'-clauses are not allowed.
\n(fn EXPR (KEYLIST BODY...)...)"
636 637
  (declare (indent 1) (debug cl-case))
  `(cl-case ,expr ,@clauses (cl--ecase-error-flag)))
Richard M. Stallman's avatar
Richard M. Stallman committed
638

639
;;;###autoload
640
(defmacro cl-typecase (expr &rest clauses)
641
  "Evals EXPR, chooses among clauses on that value.
Richard M. Stallman's avatar
Richard M. Stallman committed
642 643
Each clause looks like (TYPE BODY...).  EXPR is evaluated and, if it
satisfies TYPE, the corresponding BODY is evaluated.  If no clause succeeds,
644
cl-typecase returns nil.  A TYPE of t or `otherwise' is allowed only in the
645 646
final clause, and matches if no other keys match.
\n(fn EXPR (TYPE BODY...)...)"
647 648
  (declare (indent 1)
           (debug (form &rest ([&or cl-type-spec "otherwise"] body))))
649
  (let* ((temp (if (cl--simple-expr-p expr 3) expr (make-symbol "--cl-var--")))
Richard M. Stallman's avatar
Richard M. Stallman committed
650 651 652 653 654 655 656
	 (type-list nil)
	 (body (cons
		'cond
		(mapcar
		 (function
		  (lambda (c)
		    (cons (cond ((eq (car c) 'otherwise) t)
657 658
				((eq (car c) 'cl--ecase-error-flag)
				 `(error "cl-etypecase failed: %s, %s"
659
                                         ,temp ',(reverse type-list)))
Richard M. Stallman's avatar
Richard M. Stallman committed
660
				(t
661
				 (push (car c) type-list)
662
				 (cl--make-type-test temp (car c))))
Richard M. Stallman's avatar
Richard M. Stallman committed
663 664 665
			  (or (cdr c) '(nil)))))
		 clauses))))
    (if (eq temp expr) body
666
      `(let ((,temp ,expr)) ,body))))
Richard M. Stallman's avatar
Richard M. Stallman committed
667

668
;;;###autoload
669 670
(defmacro cl-etypecase (expr &rest clauses)
  "Like `cl-typecase', but error if no case fits.
671 672
`otherwise'-clauses are not allowed.
\n(fn EXPR (TYPE BODY...)...)"
673 674
  (declare (indent 1) (debug cl-typecase))
  `(cl-typecase ,expr ,@clauses (cl--ecase-error-flag)))
Richard M. Stallman's avatar
Richard M. Stallman committed
675 676 677 678


;;; Blocks and exits.

679
;;;###autoload
680
(defmacro cl-block (name &rest body)
681
  "Define a lexically-scoped block named NAME.
682
NAME may be any symbol.  Code inside the BODY forms can call `cl-return-from'
Richard M. Stallman's avatar
Richard M. Stallman committed
683 684 685 686 687 688
to jump prematurely out of the block.  This differs from `catch' and `throw'
in two respects:  First, the NAME is an unevaluated symbol rather than a
quoted symbol or other form; and second, NAME is lexically rather than
dynamically scoped:  Only references to it within BODY will work.  These
references may appear inside macro expansions, but not inside functions
called from BODY."
689
  (declare (indent 1) (debug (symbolp body)))
690
  (if (cl--safe-expr-p `(progn ,@body)) `(progn ,@body)
691
    `(cl--block-wrapper
692 693
      (catch ',(intern (format "--cl-block-%s--" name))
        ,@body))))
Richard M. Stallman's avatar
Richard M. Stallman committed
694

695
;;;###autoload
696
(defmacro cl-return (&optional result)
697
  "Return from the block named nil.
698
This is equivalent to `(cl-return-from nil RESULT)'."
699
  (declare (debug (&optional form)))
700
  `(cl-return-from nil ,result))
Richard M. Stallman's avatar
Richard M. Stallman committed
701

702
;;;###autoload
703
(defmacro cl-return-from (name &optional result)
704
  "Return from the block named NAME.
705
This jumps out to the innermost enclosing `(cl-block NAME ...)' form,
Richard M. Stallman's avatar
Richard M. Stallman committed
706 707 708
returning RESULT from that form (or nil if RESULT is omitted).
This is compatible with Common Lisp, but note that `defun' and
`defmacro' do not create implicit blocks as they do in Common Lisp."
709
  (declare (indent 1) (debug (symbolp &optional form)))
Richard M. Stallman's avatar
Richard M. Stallman committed
710
  (let ((name2 (intern (format "--cl-block-%s--" name))))
711
    `(cl--block-throw ',name2 ,result)))
Richard M. Stallman's avatar
Richard M. Stallman committed
712 713


714
;;; The "cl-loop" macro.
Richard M. Stallman's avatar
Richard M. Stallman committed
715

716 717 718 719 720 721 722
(defvar cl--loop-args) (defvar cl--loop-accum-var) (defvar cl--loop-accum-vars)
(defvar cl--loop-bindings) (defvar cl--loop-body) (defvar cl--loop-destr-temps)
(defvar cl--loop-finally) (defvar cl--loop-finish-flag)
(defvar cl--loop-first-flag)
(defvar cl--loop-initially) (defvar cl--loop-map-form) (defvar cl--loop-name)
(defvar cl--loop-result) (defvar cl--loop-result-explicit)
(defvar cl--loop-result-var) (defvar cl--loop-steps) (defvar cl--loop-symbol-macs)
Richard M. Stallman's avatar
Richard M. Stallman committed
723

724
;;;###autoload
725
(defmacro cl-loop (&rest loop-args)
726
  "The Common Lisp `cl-loop' macro.
Richard M. Stallman's avatar
Richard M. Stallman committed
727 728 729 730 731 732 733 734 735 736
Valid clauses are:
  for VAR from/upfrom/downfrom NUM to/upto/downto/above/below NUM by NUM,
  for VAR in LIST by FUNC, for VAR on LIST by FUNC, for VAR = INIT then EXPR,
  for VAR across ARRAY, repeat NUM, with VAR = INIT, while COND, until COND,
  always COND, never COND, thereis COND, collect EXPR into VAR,
  append EXPR into VAR, nconc EXPR into VAR, sum EXPR into VAR,
  count EXPR into VAR, maximize EXPR into VAR, minimize EXPR into VAR,
  if COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
  unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
  do EXPRS..., initially EXPRS..., finally EXPRS..., return EXPR,
737 738 739
  finally return EXPR, named NAME.

\(fn CLAUSE...)"
740
  (declare (debug (&rest &or symbolp form)))
741 742 743
  (if (not (memq t (mapcar 'symbolp (delq nil (delq t (cl-copy-list loop-args))))))
      `(cl-block nil (while t ,@loop-args))
    (let ((cl--loop-args loop-args) (cl--loop-name nil) (cl--loop-bindings nil)
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
	  (cl--loop-body nil)	(cl--loop-steps nil)
	  (cl--loop-result nil)	(cl--loop-result-explicit nil)
	  (cl--loop-result-var nil) (cl--loop-finish-flag nil)
	  (cl--loop-accum-var nil)	(cl--loop-accum-vars nil)
	  (cl--loop-initially nil)	(cl--loop-finally nil)
	  (cl--loop-map-form nil)   (cl--loop-first-flag nil)
	  (cl--loop-destr-temps nil) (cl--loop-symbol-macs nil))
      (setq cl--loop-args (append cl--loop-args '(cl-end-loop)))
      (while (not (eq (car cl--loop-args) 'cl-end-loop)) (cl-parse-loop-clause))
      (if cl--loop-finish-flag
	  (push `((,cl--loop-finish-flag t)) cl--loop-bindings))
      (if cl--loop-first-flag
	  (progn (push `((,cl--loop-first-flag t)) cl--loop-bindings)
		 (push `(setq ,cl--loop-first-flag nil) cl--loop-steps)))
      (let* ((epilogue (nconc (nreverse cl--loop-finally)
			      (list (or cl--loop-result-explicit cl--loop-result))))
	     (ands (cl--loop-build-ands (nreverse cl--loop-body)))
	     (while-body (nconc (cadr ands) (nreverse cl--loop-steps)))
Richard M. Stallman's avatar
Richard M. Stallman committed
762
	     (body (append
763 764
		    (nreverse cl--loop-initially)
		    (list (if cl--loop-map-form
765 766
			      `(cl-block --cl-finish--
                                 ,(cl-subst
767 768
                                   (if (eq (car ands) t) while-body
                                     (cons `(or ,(car ands)
769
                                                (cl-return-from --cl-finish--
770 771
                                                  nil))
                                           while-body))
772
                                   '--cl-map cl--loop-map-form))
773
			    `(while ,(car ands) ,@while-body)))
774 775 776 777
		    (if cl--loop-finish-flag
			(if (equal epilogue '(nil)) (list cl--loop-result-var)
			  `((if ,cl--loop-finish-flag
				(progn ,@epilogue) ,cl--loop-result-var)))
Richard M. Stallman's avatar
Richard M. Stallman committed
778
		      epilogue))))
779 780 781 782
	(if cl--loop-result-var (push (list cl--loop-result-var) cl--loop-bindings))
	(while cl--loop-bindings
	  (if (cdar cl--loop-bindings)
	      (setq body (list (cl--loop-let (pop cl--loop-bindings) body t)))
Richard M. Stallman's avatar
Richard M. Stallman committed
783
	    (let ((lets nil))
784 785 786 787 788 789 790
	      (while (and cl--loop-bindings
			  (not (cdar cl--loop-bindings)))
		(push (car (pop cl--loop-bindings)) lets))
	      (setq body (list (cl--loop-let lets body nil))))))
	(if cl--loop-symbol-macs
	    (setq body (list `(cl-symbol-macrolet ,cl--loop-symbol-macs ,@body))))
	`(cl-block ,cl--loop-name ,@body)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
791

792
;; Below is a complete spec for cl-loop, in several parts that correspond
793 794
;; to the syntax given in CLtL2.  The specs do more than specify where
;; the forms are; it also specifies, as much as Edebug allows, all the
795
;; syntactically valid cl-loop clauses.  The disadvantage of this
796 797 798
;; completeness is rigidity, but the "for ... being" clause allows
;; arbitrary extensions of the form: [symbolp &rest &or symbolp form].

799
;; (def-edebug-spec cl-loop
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
;;   ([&optional ["named" symbolp]]
;;    [&rest
;;     &or
;;     ["repeat" form]
;;     loop-for-as
;;     loop-with
;;     loop-initial-final]
;;    [&rest loop-clause]
;;    ))

;; (def-edebug-spec loop-with
;;   ("with" loop-var
;;    loop-type-spec
;;    [&optional ["=" form]]
;;    &rest ["and" loop-var
;; 	  loop-type-spec
;; 	  [&optional ["=" form]]]))

;; (def-edebug-spec loop-for-as
;;   ([&or "for" "as"] loop-for-as-subclause
;;    &rest ["and" loop-for-as-subclause]))

;; (def-edebug-spec loop-for-as-subclause
;;   (loop-var
;;    loop-type-spec
;;    &or
;;    [[&or "in" "on" "in-ref" "across-ref"]
;;     form &optional ["by" function-form]]

;;    ["=" form &optional ["then" form]]
;;    ["across" form]
;;    ["being"
;;     [&or "the" "each"]
;;     &or
;;     [[&or "element" "elements"]
;;      [&or "of" "in" "of-ref"] form
;;      &optional "using" ["index" symbolp]];; is this right?
;;     [[&or "hash-key" "hash-keys"
;; 	  "hash-value" "hash-values"]
;;      [&or "of" "in"]
;;      hash-table-p &optional ["using" ([&or "hash-value" "hash-values"
;; 					   "hash-key" "hash-keys"] sexp)]]

;;     [[&or "symbol" "present-symbol" "external-symbol"
;; 	  "symbols" "present-symbols" "external-symbols"]
;;      [&or "in" "of"] package-p]

;;     ;; Extensions for Emacs Lisp, including Lucid Emacs.
;;     [[&or "frame" "frames"
;; 	  "screen" "screens"
;; 	  "buffer" "buffers"]]

;;     [[&or "window" "windows"]
;;      [&or "of" "in"] form]

;;     [[&or "overlay" "overlays"
;; 	  "extent" "extents"]
;;      [&or "of" "in"] form
;;      &optional [[&or "from" "to"] form]]

;;     [[&or "interval" "intervals"]
;;      [&or "in" "of"] form
;;      &optional [[&or "from" "to"] form]
;;      ["property" form]]

;;     [[&or "key-code" "key-codes"
;; 	  "key-seq" "key-seqs"
;; 	  "key-binding" "key-bindings"]
;;      [&or "in" "of"] form
;;      &optional ["using" ([&or "key-code" "key-codes"
;; 			      "key-seq" "key-seqs"
;; 			      "key-binding" "key-bindings"]
;; 			 sexp)]]
;;     ;; For arbitrary extensions, recognize anything else.
;;     [symbolp &rest &or symbolp form]
;;     ]

;;    ;; arithmetic - must be last since all parts are optional.
;;    [[&optional [[&or "from" "downfrom" "upfrom"] form]]
;;     [&optional [[&or "to" "downto" "upto" "below" "above"] form]]
;;     [&optional ["by" form]]
;;     ]))

;; (def-edebug-spec loop-initial-final
;;   (&or ["initially"
;; 	;; [&optional &or "do" "doing"]  ;; CLtL2 doesn't allow this.
;; 	&rest loop-non-atomic-expr]
;;        ["finally" &or
;; 	[[&optional &or "do" "doing"] &rest loop-non-atomic-expr]
;; 	["return" form]]))

;; (def-edebug-spec loop-and-clause
;;   (loop-clause &rest ["and" loop-clause]))

;; (def-edebug-spec loop-clause
;;   (&or
;;    [[&or "while" "until" "always" "never" "thereis"] form]

;;    [[&or "collect" "collecting"
;; 	 "append" "appending"
;; 	 "nconc" "nconcing"
;; 	 "concat" "vconcat"] form
;; 	 [&optional ["into" loop-var]]]

;;    [[&or "count" "counting"
;; 	 "sum" "summing"
;; 	 "maximize" "maximizing"
;; 	 "minimize" "minimizing"] form
;; 	 [&optional ["into" loop-var]]
;; 	 loop-type-spec]

;;    [[&or "if" "when" "unless"]
;;     form loop-and-clause
;;     [&optional ["else" loop-and-clause]]
;;     [&optional "end"]]

;;    [[&or "do" "doing"] &rest loop-non-atomic-expr]

;;    ["return" form]
;;    loop-initial-final
;;    ))

;; (def-edebug-spec loop-non-atomic-expr
;;   ([&not atom] form))

;; (def-edebug-spec loop-var
;;   ;; The symbolp must be last alternative to recognize e.g. (a b . c)
;;   ;; loop-var =>
;;   ;; (loop-var . [&or nil loop-var])
;;   ;; (symbolp . [&or nil loop-var])
;;   ;; (symbolp . loop-var)
;;   ;; (symbolp . (symbolp . [&or nil loop-var]))
;;   ;; (symbolp . (symbolp . loop-var))
;;   ;; (symbolp . (symbolp . symbolp)) == (symbolp symbolp . symbolp)
;;   (&or (loop-var . [&or nil loop-var]) [gate symbolp]))

;; (def-edebug-spec loop-type-spec
;;   (&optional ["of-type" loop-d-type-spec]))

;; (def-edebug-spec loop-d-type-spec
;;   (&or (loop-d-type-spec . [&or nil loop-d-type-spec]) cl-type-spec))



Glenn Morris's avatar
Glenn Morris committed
944
(defun cl-parse-loop-clause ()		; uses loop-*
945
  (let ((word (pop cl--loop-args))
Richard M. Stallman's avatar
Richard M. Stallman committed
946 947 948 949 950
	(hash-types '(hash-key hash-keys hash-value hash-values))
	(key-types '(key-code key-codes key-seq key-seqs
		     key-binding key-bindings)))
    (cond

951
     ((null cl--loop-args)
952
      (error "Malformed `cl-loop' macro"))
Richard M. Stallman's avatar
Richard M. Stallman committed
953 954

     ((eq word 'named)
955
      (setq cl--loop-name (pop cl--loop-args)))
Richard M. Stallman's avatar
Richard M. Stallman committed
956 957

     ((eq word 'initially)
958 959 960 961
      (if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
      (or (consp (car cl--loop-args)) (error "Syntax error on `initially' clause"))
      (while (consp (car cl--loop-args))
	(push (pop cl--loop-args) cl--loop-initially)))
Richard M. Stallman's avatar
Richard M. Stallman committed
962 963

     ((eq word 'finally)
964 965 966 967 968 969 970 971
      (if (eq (car cl--loop-args) 'return)
	  (setq cl--loop-result-explicit (or (cl-pop2 cl--loop-args) '(quote nil)))
	(if (memq (car cl--loop-args) '(do doing)) (pop cl--loop-args))
	(or (consp (car cl--loop-args)) (error "Syntax error on `finally' clause"))
	(if (and (eq (caar cl--loop-args) 'return) (null cl--loop-name))
	    (setq cl--loop-result-explicit (or (nth 1 (pop cl--loop-args)) '(quote nil)))
	  (while (consp (car cl--loop-args))
	    (push (pop cl--loop-args) cl--loop-finally)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
972 973 974 975 976

     ((memq word '(for as))
      (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
	    (ands nil))
	(while
977
	    ;; Use `cl-gensym' rather than `make-symbol'.  It's important that
978
	    ;; (not (eq (symbol-name var1) (symbol-name var2))) because
979 980 981 982 983
	    ;; these vars get added to the macro-environment.
	    (let ((var (or (pop cl--loop-args) (cl-gensym "--cl-var--"))))
	      (setq word (pop cl--loop-args))
	      (if (eq word 'being) (setq word (pop cl--loop-args)))
	      (if (memq word '(the each)) (setq word (pop cl--loop-args)))
Richard M. Stallman's avatar
Richard M. Stallman committed
984
	      (if (memq word '(buffer buffers))
985
		  (setq word 'in cl--loop-args (cons '(buffer-list) cl--loop-args)))
Richard M. Stallman's avatar
Richard M. Stallman committed
986 987 988 989
	      (cond

	       ((memq word '(from downfrom upfrom to downto upto
			     above below by))
990 991
		(push word cl--loop-args)
		(if (memq (car cl--loop-args) '(downto above))
992
		    (error "Must specify `from' value for downward cl-loop"))
993 994 995 996 997 998 999
		(let* ((down (or (eq (car cl--loop-args) 'downfrom)
				 (memq (cl-caddr cl--loop-args) '(downto above))))
		       (excl (or (memq (car cl--loop-args) '(above below))
				 (memq (cl-caddr cl--loop-args) '(above below))))
		       (start (and (memq (car cl--loop-args) '(from upfrom downfrom))
				   (cl-pop2 cl--loop-args)))
		       (end (and (memq (car cl--loop-args)
Richard M. Stallman's avatar
Richard M. Stallman committed
1000
				       '(to upto downto above below))
1001 1002 1003
				 (cl-pop2 cl--loop-args)))
		       (step (and (eq (car cl--loop-args) 'by) (cl-pop2 cl--loop-args)))
		       (end-var (and (not (macroexp-const-p end))
1004
				     (make-symbol "--cl-var--")))
1005
		       (step-var (and (not (macroexp-const-p step))
1006
				      (make-symbol "--cl-var--"))))
Richard M. Stallman's avatar
Richard M. Stallman committed
1007 1008
		  (and step (numberp step) (<= step 0)
		       (error "Loop `by' value is not positive: %s" step))