1.0.21.1: address TYPE-WARNING in CLOS allocator for funcallable structures
[sbcl.git] / src / code / loop.lisp
1 ;;;; the LOOP iteration macro
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This code was modified by William Harold Newman beginning
7 ;;;; 19981106, originally to conform to the new SBCL bootstrap package
8 ;;;; system and then subsequently to address other cross-compiling
9 ;;;; bootstrap issues, SBCLification (e.g. DECLARE used to check
10 ;;;; argument types), and other maintenance. Whether or not it then
11 ;;;; supported all the environments implied by the reader conditionals
12 ;;;; in the source code (e.g. #!+CLOE-RUNTIME) before that
13 ;;;; modification, it sure doesn't now. It might perhaps, by blind
14 ;;;; luck, be appropriate for some other CMU-CL-derived system, but
15 ;;;; really it only attempts to be appropriate for SBCL.
16
17 ;;;; This software is derived from software originally released by the
18 ;;;; Massachusetts Institute of Technology and Symbolics, Inc. Copyright and
19 ;;;; release statements follow. Later modifications to the software are in
20 ;;;; the public domain and are provided with absolutely no warranty. See the
21 ;;;; COPYING and CREDITS files for more information.
22
23 ;;;; Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute
24 ;;;; of Technology. All Rights Reserved.
25 ;;;;
26 ;;;; Permission to use, copy, modify and distribute this software and its
27 ;;;; documentation for any purpose and without fee is hereby granted,
28 ;;;; provided that the M.I.T. copyright notice appear in all copies and that
29 ;;;; both that copyright notice and this permission notice appear in
30 ;;;; supporting documentation. The names "M.I.T." and "Massachusetts
31 ;;;; Institute of Technology" may not be used in advertising or publicity
32 ;;;; pertaining to distribution of the software without specific, written
33 ;;;; prior permission. Notice must be given in supporting documentation that
34 ;;;; copying distribution is by permission of M.I.T. M.I.T. makes no
35 ;;;; representations about the suitability of this software for any purpose.
36 ;;;; It is provided "as is" without express or implied warranty.
37 ;;;;
38 ;;;;      Massachusetts Institute of Technology
39 ;;;;      77 Massachusetts Avenue
40 ;;;;      Cambridge, Massachusetts  02139
41 ;;;;      United States of America
42 ;;;;      +1-617-253-1000
43
44 ;;;; Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics,
45 ;;;; Inc. All Rights Reserved.
46 ;;;;
47 ;;;; Permission to use, copy, modify and distribute this software and its
48 ;;;; documentation for any purpose and without fee is hereby granted,
49 ;;;; provided that the Symbolics copyright notice appear in all copies and
50 ;;;; that both that copyright notice and this permission notice appear in
51 ;;;; supporting documentation. The name "Symbolics" may not be used in
52 ;;;; advertising or publicity pertaining to distribution of the software
53 ;;;; without specific, written prior permission. Notice must be given in
54 ;;;; supporting documentation that copying distribution is by permission of
55 ;;;; Symbolics. Symbolics makes no representations about the suitability of
56 ;;;; this software for any purpose. It is provided "as is" without express
57 ;;;; or implied warranty.
58 ;;;;
59 ;;;; Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
60 ;;;; and Zetalisp are registered trademarks of Symbolics, Inc.
61 ;;;;
62 ;;;;      Symbolics, Inc.
63 ;;;;      8 New England Executive Park, East
64 ;;;;      Burlington, Massachusetts  01803
65 ;;;;      United States of America
66 ;;;;      +1-617-221-1000
67
68 (in-package "SB!LOOP")
69
70 ;;;; The design of this LOOP is intended to permit, using mostly the same
71 ;;;; kernel of code, up to three different "loop" macros:
72 ;;;;
73 ;;;; (1) The unextended, unextensible ANSI standard LOOP;
74 ;;;;
75 ;;;; (2) A clean "superset" extension of the ANSI LOOP which provides
76 ;;;; functionality similar to that of the old LOOP, but "in the style of"
77 ;;;; the ANSI LOOP. For instance, user-definable iteration paths, with a
78 ;;;; somewhat cleaned-up interface.
79 ;;;;
80 ;;;; (3) Extensions provided in another file which can make this LOOP
81 ;;;; kernel behave largely compatibly with the Genera-vintage LOOP macro,
82 ;;;; with only a small addition of code (instead of two whole, separate,
83 ;;;; LOOP macros).
84 ;;;;
85 ;;;; Each of the above three LOOP variations can coexist in the same LISP
86 ;;;; environment.
87 ;;;;
88 ;;;; KLUDGE: In SBCL, we only really use variant (1), and any generality
89 ;;;; for the other variants is wasted. -- WHN 20000121
90
91 ;;;; FIXME: the STEP-FUNCTION stuff in the code seems to've been
92 ;;;; intended to support code which was conditionalized with
93 ;;;; LOOP-PREFER-POP (not true on CMU CL) and which has since been
94 ;;;; removed. Thus, STEP-FUNCTION stuff could probably be removed too.
95 \f
96 ;;;; list collection macrology
97
98 (sb!int:defmacro-mundanely with-loop-list-collection-head
99     ((head-var tail-var &optional user-head-var) &body body)
100   (let ((l (and user-head-var (list (list user-head-var nil)))))
101     `(let* ((,head-var (list nil)) (,tail-var ,head-var) ,@l)
102        ,@body)))
103
104 (sb!int:defmacro-mundanely loop-collect-rplacd
105     (&environment env (head-var tail-var &optional user-head-var) form)
106   (setq form (sb!xc:macroexpand form env))
107   (flet ((cdr-wrap (form n)
108            (declare (fixnum n))
109            (do () ((<= n 4) (setq form `(,(case n
110                                             (1 'cdr)
111                                             (2 'cddr)
112                                             (3 'cdddr)
113                                             (4 'cddddr))
114                                          ,form)))
115              (setq form `(cddddr ,form) n (- n 4)))))
116     (let ((tail-form form) (ncdrs nil))
117       ;; Determine whether the form being constructed is a list of known
118       ;; length.
119       (when (consp form)
120         (cond ((eq (car form) 'list)
121                (setq ncdrs (1- (length (cdr form)))))
122               ((member (car form) '(list* cons))
123                (when (and (cddr form) (member (car (last form)) '(nil 'nil)))
124                  (setq ncdrs (- (length (cdr form)) 2))))))
125       (let ((answer
126               (cond ((null ncdrs)
127                      `(when (setf (cdr ,tail-var) ,tail-form)
128                         (setq ,tail-var (last (cdr ,tail-var)))))
129                     ((< ncdrs 0) (return-from loop-collect-rplacd nil))
130                     ((= ncdrs 0)
131                      ;; @@@@ Here we have a choice of two idioms:
132                      ;;   (RPLACD TAIL (SETQ TAIL TAIL-FORM))
133                      ;;   (SETQ TAIL (SETF (CDR TAIL) TAIL-FORM)).
134                      ;; Genera and most others I have seen do better with the
135                      ;; former.
136                      `(rplacd ,tail-var (setq ,tail-var ,tail-form)))
137                     (t `(setq ,tail-var ,(cdr-wrap `(setf (cdr ,tail-var)
138                                                           ,tail-form)
139                                                    ncdrs))))))
140         ;; If not using locatives or something similar to update the
141         ;; user's head variable, we've got to set it... It's harmless
142         ;; to repeatedly set it unconditionally, and probably faster
143         ;; than checking.
144         (when user-head-var
145           (setq answer
146                 `(progn ,answer
147                         (setq ,user-head-var (cdr ,head-var)))))
148         answer))))
149
150 (sb!int:defmacro-mundanely loop-collect-answer (head-var
151                                                    &optional user-head-var)
152   (or user-head-var
153       `(cdr ,head-var)))
154 \f
155 ;;;; maximization technology
156
157 #|
158 The basic idea of all this minimax randomness here is that we have to
159 have constructed all uses of maximize and minimize to a particular
160 "destination" before we can decide how to code them. The goal is to not
161 have to have any kinds of flags, by knowing both that (1) the type is
162 something which we can provide an initial minimum or maximum value for
163 and (2) know that a MAXIMIZE and MINIMIZE are not being combined.
164
165 SO, we have a datastructure which we annotate with all sorts of things,
166 incrementally updating it as we generate loop body code, and then use
167 a wrapper and internal macros to do the coding when the loop has been
168 constructed.
169 |#
170
171 (defstruct (loop-minimax
172              (:constructor make-loop-minimax-internal)
173              (:copier nil)
174              (:predicate nil))
175   answer-variable
176   type
177   temp-variable
178   flag-variable
179   operations
180   infinity-data)
181
182 (defvar *loop-minimax-type-infinities-alist*
183   ;; FIXME: Now that SBCL supports floating point infinities again, we
184   ;; should have floating point infinities here, as cmucl-2.4.8 did.
185   '((fixnum most-positive-fixnum most-negative-fixnum)))
186
187 (defun make-loop-minimax (answer-variable type)
188   (let ((infinity-data (cdr (assoc type
189                                    *loop-minimax-type-infinities-alist*
190                                    :test #'sb!xc:subtypep))))
191     (make-loop-minimax-internal
192       :answer-variable answer-variable
193       :type type
194       :temp-variable (gensym "LOOP-MAXMIN-TEMP-")
195       :flag-variable (and (not infinity-data)
196                           (gensym "LOOP-MAXMIN-FLAG-"))
197       :operations nil
198       :infinity-data infinity-data)))
199
200 (defun loop-note-minimax-operation (operation minimax)
201   (pushnew (the symbol operation) (loop-minimax-operations minimax))
202   (when (and (cdr (loop-minimax-operations minimax))
203              (not (loop-minimax-flag-variable minimax)))
204     (setf (loop-minimax-flag-variable minimax)
205           (gensym "LOOP-MAXMIN-FLAG-")))
206   operation)
207
208 (sb!int:defmacro-mundanely with-minimax-value (lm &body body)
209   (let ((init (loop-typed-init (loop-minimax-type lm)))
210         (which (car (loop-minimax-operations lm)))
211         (infinity-data (loop-minimax-infinity-data lm))
212         (answer-var (loop-minimax-answer-variable lm))
213         (temp-var (loop-minimax-temp-variable lm))
214         (flag-var (loop-minimax-flag-variable lm))
215         (type (loop-minimax-type lm)))
216     (if flag-var
217         `(let ((,answer-var ,init) (,temp-var ,init) (,flag-var nil))
218            (declare (type ,type ,answer-var ,temp-var))
219            ,@body)
220         `(let ((,answer-var ,(if (eq which 'min)
221                                  (first infinity-data)
222                                  (second infinity-data)))
223                (,temp-var ,init))
224            (declare (type ,type ,answer-var ,temp-var))
225            ,@body))))
226
227 (sb!int:defmacro-mundanely loop-accumulate-minimax-value (lm operation form)
228   (let* ((answer-var (loop-minimax-answer-variable lm))
229          (temp-var (loop-minimax-temp-variable lm))
230          (flag-var (loop-minimax-flag-variable lm))
231          (test `(,(ecase operation
232                     (min '<)
233                     (max '>))
234                  ,temp-var ,answer-var)))
235     `(progn
236        (setq ,temp-var ,form)
237        (when ,(if flag-var `(or (not ,flag-var) ,test) test)
238          (setq ,@(and flag-var `(,flag-var t))
239                ,answer-var ,temp-var)))))
240 \f
241 ;;;; LOOP keyword tables
242
243 #|
244 LOOP keyword tables are hash tables string keys and a test of EQUAL.
245
246 The actual descriptive/dispatch structure used by LOOP is called a "loop
247 universe" contains a few tables and parameterizations. The basic idea is
248 that we can provide a non-extensible ANSI-compatible loop environment,
249 an extensible ANSI-superset loop environment, and (for such environments
250 as CLOE) one which is "sufficiently close" to the old Genera-vintage
251 LOOP for use by old user programs without requiring all of the old LOOP
252 code to be loaded.
253 |#
254
255 ;;;; token hackery
256
257 ;;; Compare two "tokens". The first is the frob out of *LOOP-SOURCE-CODE*,
258 ;;; the second a symbol to check against.
259 (defun loop-tequal (x1 x2)
260   (and (symbolp x1) (string= x1 x2)))
261
262 (defun loop-tassoc (kwd alist)
263   (and (symbolp kwd) (assoc kwd alist :test #'string=)))
264
265 (defun loop-tmember (kwd list)
266   (and (symbolp kwd) (member kwd list :test #'string=)))
267
268 (defun loop-lookup-keyword (loop-token table)
269   (and (symbolp loop-token)
270        (values (gethash (symbol-name loop-token) table))))
271
272 (sb!int:defmacro-mundanely loop-store-table-data (symbol table datum)
273   `(setf (gethash (symbol-name ,symbol) ,table) ,datum))
274
275 (defstruct (loop-universe
276              (:copier nil)
277              (:predicate nil))
278   keywords             ; hash table, value = (fn-name . extra-data)
279   iteration-keywords   ; hash table, value = (fn-name . extra-data)
280   for-keywords         ; hash table, value = (fn-name . extra-data)
281   path-keywords        ; hash table, value = (fn-name . extra-data)
282   type-symbols         ; hash table of type SYMBOLS, test EQ,
283                        ; value = CL type specifier
284   type-keywords        ; hash table of type STRINGS, test EQUAL,
285                        ; value = CL type spec
286   ansi                 ; NIL, T, or :EXTENDED
287   implicit-for-required) ; see loop-hack-iteration
288 (sb!int:def!method print-object ((u loop-universe) stream)
289   (let ((string (case (loop-universe-ansi u)
290                   ((nil) "non-ANSI")
291                   ((t) "ANSI")
292                   (:extended "extended-ANSI")
293                   (t (loop-universe-ansi u)))))
294     (print-unreadable-object (u stream :type t)
295       (write-string string stream))))
296
297 ;;; This is the "current" loop context in use when we are expanding a
298 ;;; loop. It gets bound on each invocation of LOOP.
299 (defvar *loop-universe*)
300
301 (defun make-standard-loop-universe (&key keywords for-keywords
302                                          iteration-keywords path-keywords
303                                          type-keywords type-symbols ansi)
304   (declare (type (member nil t :extended) ansi))
305   (flet ((maketable (entries)
306            (let* ((size (length entries))
307                   (ht (make-hash-table :size (if (< size 10) 10 size)
308                                        :test 'equal)))
309              (dolist (x entries)
310                (setf (gethash (symbol-name (car x)) ht) (cadr x)))
311              ht)))
312     (make-loop-universe
313       :keywords (maketable keywords)
314       :for-keywords (maketable for-keywords)
315       :iteration-keywords (maketable iteration-keywords)
316       :path-keywords (maketable path-keywords)
317       :ansi ansi
318       :implicit-for-required (not (null ansi))
319       :type-keywords (maketable type-keywords)
320       :type-symbols (let* ((size (length type-symbols))
321                            (ht (make-hash-table :size (if (< size 10) 10 size)
322                                                 :test 'eq)))
323                       (dolist (x type-symbols)
324                         (if (atom x)
325                             (setf (gethash x ht) x)
326                             (setf (gethash (car x) ht) (cadr x))))
327                       ht))))
328 \f
329 ;;;; SETQ hackery, including destructuring ("DESETQ")
330
331 (defun loop-make-psetq (frobs)
332   (and frobs
333        (loop-make-desetq
334          (list (car frobs)
335                (if (null (cddr frobs)) (cadr frobs)
336                    `(prog1 ,(cadr frobs)
337                            ,(loop-make-psetq (cddr frobs))))))))
338
339 (defun loop-make-desetq (var-val-pairs)
340   (if (null var-val-pairs)
341       nil
342       (cons 'loop-really-desetq var-val-pairs)))
343
344 (defvar *loop-desetq-temporary*
345         (make-symbol "LOOP-DESETQ-TEMP"))
346
347 (sb!int:defmacro-mundanely loop-really-desetq (&environment env
348                                                &rest var-val-pairs)
349   (labels ((find-non-null (var)
350              ;; See whether there's any non-null thing here. Recurse
351              ;; if the list element is itself a list.
352              (do ((tail var)) ((not (consp tail)) tail)
353                (when (find-non-null (pop tail)) (return t))))
354            (loop-desetq-internal (var val &optional temp)
355              ;; returns a list of actions to be performed
356              (typecase var
357                (null
358                  (when (consp val)
359                    ;; Don't lose possible side effects.
360                    (if (eq (car val) 'prog1)
361                        ;; These can come from PSETQ or DESETQ below.
362                        ;; Throw away the value, keep the side effects.
363                        ;; Special case is for handling an expanded POP.
364                        (mapcan (lambda (x)
365                                  (and (consp x)
366                                       (or (not (eq (car x) 'car))
367                                           (not (symbolp (cadr x)))
368                                           (not (symbolp (setq x (sb!xc:macroexpand x env)))))
369                                       (cons x nil)))
370                                (cdr val))
371                        `(,val))))
372                (cons
373                  (let* ((car (car var))
374                         (cdr (cdr var))
375                         (car-non-null (find-non-null car))
376                         (cdr-non-null (find-non-null cdr)))
377                    (when (or car-non-null cdr-non-null)
378                      (if cdr-non-null
379                          (let* ((temp-p temp)
380                                 (temp (or temp *loop-desetq-temporary*))
381                                 (body `(,@(loop-desetq-internal car
382                                                                 `(car ,temp))
383                                           (setq ,temp (cdr ,temp))
384                                           ,@(loop-desetq-internal cdr
385                                                                   temp
386                                                                   temp))))
387                            (if temp-p
388                                `(,@(unless (eq temp val)
389                                      `((setq ,temp ,val)))
390                                  ,@body)
391                                `((let ((,temp ,val))
392                                    ,@body))))
393                          ;; no CDRing to do
394                          (loop-desetq-internal car `(car ,val) temp)))))
395                (otherwise
396                  (unless (eq var val)
397                    `((setq ,var ,val)))))))
398     (do ((actions))
399         ((null var-val-pairs)
400          (if (null (cdr actions)) (car actions) `(progn ,@(nreverse actions))))
401       (setq actions (revappend
402                       (loop-desetq-internal (pop var-val-pairs)
403                                             (pop var-val-pairs))
404                       actions)))))
405 \f
406 ;;;; LOOP-local variables
407
408 ;;; This is the "current" pointer into the LOOP source code.
409 (defvar *loop-source-code*)
410
411 ;;; This is the pointer to the original, for things like NAMED that
412 ;;; insist on being in a particular position
413 (defvar *loop-original-source-code*)
414
415 ;;; This is *loop-source-code* as of the "last" clause. It is used
416 ;;; primarily for generating error messages (see loop-error, loop-warn).
417 (defvar *loop-source-context*)
418
419 ;;; list of names for the LOOP, supplied by the NAMED clause
420 (defvar *loop-names*)
421
422 ;;; The macroexpansion environment given to the macro.
423 (defvar *loop-macro-environment*)
424
425 ;;; This holds variable names specified with the USING clause.
426 ;;; See LOOP-NAMED-VAR.
427 (defvar *loop-named-vars*)
428
429 ;;; LETlist-like list being accumulated for current group of bindings.
430 (defvar *loop-vars*)
431
432 ;;; List of declarations being accumulated in parallel with
433 ;;; *LOOP-VARS*.
434 (defvar *loop-declarations*)
435
436 ;;; This is used by LOOP for destructuring binding, if it is doing
437 ;;; that itself. See LOOP-MAKE-VAR.
438 (defvar *loop-desetq-crocks*)
439
440 ;;; list of wrapping forms, innermost first, which go immediately
441 ;;; inside the current set of parallel bindings being accumulated in
442 ;;; *LOOP-VARS*. The wrappers are appended onto a body. E.g., this
443 ;;; list could conceivably have as its value
444 ;;;   ((WITH-OPEN-FILE (G0001 G0002 ...))),
445 ;;; with G0002 being one of the bindings in *LOOP-VARS* (This is why
446 ;;; the wrappers go inside of the variable bindings).
447 (defvar *loop-wrappers*)
448
449 ;;; This accumulates lists of previous values of *LOOP-VARS* and the
450 ;;; other lists above, for each new nesting of bindings. See
451 ;;; LOOP-BIND-BLOCK.
452 (defvar *loop-bind-stack*)
453
454 ;;; list of prologue forms of the loop, accumulated in reverse order
455 (defvar *loop-prologue*)
456
457 (defvar *loop-before-loop*)
458 (defvar *loop-body*)
459 (defvar *loop-after-body*)
460
461 ;;; This is T if we have emitted any body code, so that iteration
462 ;;; driving clauses can be disallowed. This is not strictly the same
463 ;;; as checking *LOOP-BODY*, because we permit some clauses such as
464 ;;; RETURN to not be considered "real" body (so as to permit the user
465 ;;; to "code" an abnormal return value "in loop").
466 (defvar *loop-emitted-body*)
467
468 ;;; list of epilogue forms (supplied by FINALLY generally), accumulated
469 ;;; in reverse order
470 (defvar *loop-epilogue*)
471
472 ;;; list of epilogue forms which are supplied after the above "user"
473 ;;; epilogue. "Normal" termination return values are provide by
474 ;;; putting the return form in here. Normally this is done using
475 ;;; LOOP-EMIT-FINAL-VALUE, q.v.
476 (defvar *loop-after-epilogue*)
477
478 ;;; the "culprit" responsible for supplying a final value from the
479 ;;; loop. This is so LOOP-DISALLOW-AGGREGATE-BOOLEANS can moan about
480 ;;; disallowed anonymous collections.
481 (defvar *loop-final-value-culprit*)
482
483 ;;; If this is true, we are in some branch of a conditional. Some
484 ;;; clauses may be disallowed.
485 (defvar *loop-inside-conditional*)
486
487 ;;; If not NIL, this is a temporary bound around the loop for holding
488 ;;; the temporary value for "it" in things like "when (f) collect it".
489 ;;; It may be used as a supertemporary by some other things.
490 (defvar *loop-when-it-var*)
491
492 ;;; Sometimes we decide we need to fold together parts of the loop,
493 ;;; but some part of the generated iteration code is different for the
494 ;;; first and remaining iterations. This variable will be the
495 ;;; temporary which is the flag used in the loop to tell whether we
496 ;;; are in the first or remaining iterations.
497 (defvar *loop-never-stepped-var*)
498
499 ;;; list of all the value-accumulation descriptor structures in the
500 ;;; loop. See LOOP-GET-COLLECTION-INFO.
501 (defvar *loop-collection-cruft*) ; for multiple COLLECTs (etc.)
502 \f
503 ;;;; code analysis stuff
504
505 (defun loop-constant-fold-if-possible (form &optional expected-type)
506   (let* ((constantp (sb!xc:constantp form))
507          (value (and constantp (sb!int:constant-form-value form))))
508     (when (and constantp expected-type)
509       (unless (sb!xc:typep value expected-type)
510         (loop-warn "~@<The form ~S evaluated to ~S, which was not of ~
511                     the anticipated type ~S.~:@>"
512                    form value expected-type)
513         (setq constantp nil value nil)))
514     (values form constantp value)))
515 \f
516 ;;;; LOOP iteration optimization
517
518 (defvar *loop-duplicate-code* nil)
519
520 (defvar *loop-iteration-flag-var* (make-symbol "LOOP-NOT-FIRST-TIME"))
521
522 (defun loop-code-duplication-threshold (env)
523   (declare (ignore env))
524   (let (;; If we could read optimization declaration information (as
525         ;; with the DECLARATION-INFORMATION function (present in
526         ;; CLTL2, removed from ANSI standard) we could set these
527         ;; values flexibly. Without DECLARATION-INFORMATION, we have
528         ;; to set them to constants.
529         ;;
530         ;; except FIXME: we've lost all pretence of portability,
531         ;; considering this instead an internal implementation, so
532         ;; we're free to couple to our own representation of the
533         ;; environment.
534         (speed 1)
535         (space 1))
536     (+ 40 (* (- speed space) 10))))
537
538 (sb!int:defmacro-mundanely loop-body (&environment env
539                                          prologue
540                                          before-loop
541                                          main-body
542                                          after-loop
543                                          epilogue
544                                          &aux rbefore rafter flagvar)
545   (unless (= (length before-loop) (length after-loop))
546     (error "LOOP-BODY called with non-synched before- and after-loop lists"))
547   ;;All our work is done from these copies, working backwards from the end:
548   (setq rbefore (reverse before-loop) rafter (reverse after-loop))
549   (labels ((psimp (l)
550              (let ((ans nil))
551                (dolist (x l)
552                  (when x
553                    (push x ans)
554                    (when (and (consp x)
555                               (member (car x) '(go return return-from)))
556                      (return nil))))
557                (nreverse ans)))
558            (pify (l) (if (null (cdr l)) (car l) `(progn ,@l)))
559            (makebody ()
560              (let ((form `(tagbody
561                             ,@(psimp (append prologue (nreverse rbefore)))
562                          next-loop
563                             ,@(psimp (append main-body
564                                              (nreconc rafter
565                                                       `((go next-loop)))))
566                          end-loop
567                             ,@(psimp epilogue))))
568                (if flagvar `(let ((,flagvar nil)) ,form) form))))
569     (when (or *loop-duplicate-code* (not rbefore))
570       (return-from loop-body (makebody)))
571     ;; This outer loop iterates once for each not-first-time flag test
572     ;; generated plus once more for the forms that don't need a flag test.
573     (do ((threshold (loop-code-duplication-threshold env))) (nil)
574       (declare (fixnum threshold))
575       ;; Go backwards from the ends of before-loop and after-loop
576       ;; merging all the equivalent forms into the body.
577       (do () ((or (null rbefore) (not (equal (car rbefore) (car rafter)))))
578         (push (pop rbefore) main-body)
579         (pop rafter))
580       (unless rbefore (return (makebody)))
581       ;; The first forms in RBEFORE & RAFTER (which are the
582       ;; chronologically last forms in the list) differ, therefore
583       ;; they cannot be moved into the main body. If everything that
584       ;; chronologically precedes them either differs or is equal but
585       ;; is okay to duplicate, we can just put all of rbefore in the
586       ;; prologue and all of rafter after the body. Otherwise, there
587       ;; is something that is not okay to duplicate, so it and
588       ;; everything chronologically after it in rbefore and rafter
589       ;; must go into the body, with a flag test to distinguish the
590       ;; first time around the loop from later times. What
591       ;; chronologically precedes the non-duplicatable form will be
592       ;; handled the next time around the outer loop.
593       (do ((bb rbefore (cdr bb))
594            (aa rafter (cdr aa))
595            (lastdiff nil)
596            (count 0)
597            (inc nil))
598           ((null bb) (return-from loop-body (makebody)))        ; Did it.
599         (cond ((not (equal (car bb) (car aa))) (setq lastdiff bb count 0))
600               ((or (not (setq inc (estimate-code-size (car bb) env)))
601                    (> (incf count inc) threshold))
602                ;; Ok, we have found a non-duplicatable piece of code.
603                ;; Everything chronologically after it must be in the
604                ;; central body. Everything chronologically at and
605                ;; after LASTDIFF goes into the central body under a
606                ;; flag test.
607                (let ((then nil) (else nil))
608                  (do () (nil)
609                    (push (pop rbefore) else)
610                    (push (pop rafter) then)
611                    (when (eq rbefore (cdr lastdiff)) (return)))
612                  (unless flagvar
613                    (push `(setq ,(setq flagvar *loop-iteration-flag-var*)
614                                 t)
615                          else))
616                  (push `(if ,flagvar ,(pify (psimp then)) ,(pify (psimp else)))
617                        main-body))
618                ;; Everything chronologically before lastdiff until the
619                ;; non-duplicatable form (CAR BB) is the same in
620                ;; RBEFORE and RAFTER, so just copy it into the body.
621                (do () (nil)
622                  (pop rafter)
623                  (push (pop rbefore) main-body)
624                  (when (eq rbefore (cdr bb)) (return)))
625                (return)))))))
626 \f
627 (defun duplicatable-code-p (expr env)
628   (if (null expr) 0
629       (let ((ans (estimate-code-size expr env)))
630         (declare (fixnum ans))
631         ;; @@@@ Use (DECLARATION-INFORMATION 'OPTIMIZE ENV) here to
632         ;; get an alist of optimize quantities back to help quantify
633         ;; how much code we are willing to duplicate.
634         ans)))
635
636 (defvar *special-code-sizes*
637         '((return 0) (progn 0)
638           (null 1) (not 1) (eq 1) (car 1) (cdr 1)
639           (when 1) (unless 1) (if 1)
640           (caar 2) (cadr 2) (cdar 2) (cddr 2)
641           (caaar 3) (caadr 3) (cadar 3) (caddr 3)
642           (cdaar 3) (cdadr 3) (cddar 3) (cdddr 3)
643           (caaaar 4) (caaadr 4) (caadar 4) (caaddr 4)
644           (cadaar 4) (cadadr 4) (caddar 4) (cadddr 4)
645           (cdaaar 4) (cdaadr 4) (cdadar 4) (cdaddr 4)
646           (cddaar 4) (cddadr 4) (cdddar 4) (cddddr 4)))
647
648 (defvar *estimate-code-size-punt*
649         '(block
650            do do* dolist
651            flet
652            labels lambda let let* locally
653            macrolet multiple-value-bind
654            prog prog*
655            symbol-macrolet
656            tagbody
657            unwind-protect
658            with-open-file))
659
660 (defun destructuring-size (x)
661   (do ((x x (cdr x)) (n 0 (+ (destructuring-size (car x)) n)))
662       ((atom x) (+ n (if (null x) 0 1)))))
663
664 (defun estimate-code-size (x env)
665   (catch 'estimate-code-size
666     (estimate-code-size-1 x env)))
667
668 (defun estimate-code-size-1 (x env)
669   (flet ((list-size (l)
670            (let ((n 0))
671              (declare (fixnum n))
672              (dolist (x l n) (incf n (estimate-code-size-1 x env))))))
673     ;;@@@@ ???? (declare (function list-size (list) fixnum))
674     (cond ((constantp x) 1)
675           ((symbolp x) (multiple-value-bind (new-form expanded-p)
676                            (sb!xc:macroexpand-1 x env)
677                          (if expanded-p
678                              (estimate-code-size-1 new-form env)
679                              1)))
680           ((atom x) 1) ;; ??? self-evaluating???
681           ((symbolp (car x))
682            (let ((fn (car x)) (tem nil) (n 0))
683              (declare (symbol fn) (fixnum n))
684              (macrolet ((f (overhead &optional (args nil args-p))
685                           `(the fixnum (+ (the fixnum ,overhead)
686                                           (the fixnum
687                                                (list-size ,(if args-p
688                                                                args
689                                                              '(cdr x))))))))
690                (cond ((setq tem (get fn 'estimate-code-size))
691                       (typecase tem
692                         (fixnum (f tem))
693                         (t (funcall tem x env))))
694                      ((setq tem (assoc fn *special-code-sizes*))
695                       (f (second tem)))
696                      ((eq fn 'cond)
697                       (dolist (clause (cdr x) n)
698                         (incf n (list-size clause)) (incf n)))
699                      ((eq fn 'desetq)
700                       (do ((l (cdr x) (cdr l))) ((null l) n)
701                         (setq n (+ n
702                                    (destructuring-size (car l))
703                                    (estimate-code-size-1 (cadr l) env)))))
704                      ((member fn '(setq psetq))
705                       (do ((l (cdr x) (cdr l))) ((null l) n)
706                         (setq n (+ n (estimate-code-size-1 (cadr l) env) 1))))
707                      ((eq fn 'go) 1)
708                      ((eq fn 'function)
709                       (if (sb!int:legal-fun-name-p (cadr x))
710                           1
711                           ;; FIXME: This tag appears not to be present
712                           ;; anywhere.
713                           (throw 'duplicatable-code-p nil)))
714                      ((eq fn 'multiple-value-setq)
715                       (f (length (second x)) (cddr x)))
716                      ((eq fn 'return-from)
717                       (1+ (estimate-code-size-1 (third x) env)))
718                      ((or (special-operator-p fn)
719                           (member fn *estimate-code-size-punt*))
720                       (throw 'estimate-code-size nil))
721                      (t (multiple-value-bind (new-form expanded-p)
722                             (sb!xc:macroexpand-1 x env)
723                           (if expanded-p
724                               (estimate-code-size-1 new-form env)
725                               (f 3))))))))
726           (t (throw 'estimate-code-size nil)))))
727 \f
728 ;;;; loop errors
729
730 (defun loop-context ()
731   (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
732       ((eq l (cdr *loop-source-code*)) (nreverse new))))
733
734 (defun loop-error (format-string &rest format-args)
735   (error 'sb!int:simple-program-error
736          :format-control "~?~%current LOOP context:~{ ~S~}."
737          :format-arguments (list format-string format-args (loop-context))))
738
739 (defun loop-warn (format-string &rest format-args)
740   (warn "~?~%current LOOP context:~{ ~S~}."
741         format-string
742         format-args
743         (loop-context)))
744
745 (defun loop-check-data-type (specified-type required-type
746                              &optional (default-type required-type))
747   (if (null specified-type)
748       default-type
749       (multiple-value-bind (a b) (sb!xc:subtypep specified-type required-type)
750         (cond ((not b)
751                (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
752                           specified-type required-type))
753               ((not a)
754                (loop-error "The specified data type ~S is not a subtype of ~S."
755                            specified-type required-type)))
756         specified-type)))
757 \f
758 (defun subst-gensyms-for-nil (tree)
759   (declare (special *ignores*))
760   (cond
761     ((null tree) (car (push (gensym "LOOP-IGNORED-VAR-") *ignores*)))
762     ((atom tree) tree)
763     (t (cons (subst-gensyms-for-nil (car tree))
764              (subst-gensyms-for-nil (cdr tree))))))
765
766 (sb!int:defmacro-mundanely loop-destructuring-bind
767     (lambda-list arg-list &rest body)
768   (let ((*ignores* nil))
769     (declare (special *ignores*))
770     (let ((d-var-lambda-list (subst-gensyms-for-nil lambda-list)))
771       `(destructuring-bind ,d-var-lambda-list
772            ,arg-list
773          (declare (ignore ,@*ignores*))
774          ,@body))))
775
776 (defun loop-build-destructuring-bindings (crocks forms)
777   (if crocks
778       `((loop-destructuring-bind ,(car crocks) ,(cadr crocks)
779         ,@(loop-build-destructuring-bindings (cddr crocks) forms)))
780       forms))
781
782 (defun loop-translate (*loop-source-code*
783                        *loop-macro-environment*
784                        *loop-universe*)
785   (let ((*loop-original-source-code* *loop-source-code*)
786         (*loop-source-context* nil)
787         (*loop-vars* nil)
788         (*loop-named-vars* nil)
789         (*loop-declarations* nil)
790         (*loop-desetq-crocks* nil)
791         (*loop-bind-stack* nil)
792         (*loop-prologue* nil)
793         (*loop-wrappers* nil)
794         (*loop-before-loop* nil)
795         (*loop-body* nil)
796         (*loop-emitted-body* nil)
797         (*loop-after-body* nil)
798         (*loop-epilogue* nil)
799         (*loop-after-epilogue* nil)
800         (*loop-final-value-culprit* nil)
801         (*loop-inside-conditional* nil)
802         (*loop-when-it-var* nil)
803         (*loop-never-stepped-var* nil)
804         (*loop-names* nil)
805         (*loop-collection-cruft* nil))
806     (loop-iteration-driver)
807     (loop-bind-block)
808     (let ((answer `(loop-body
809                      ,(nreverse *loop-prologue*)
810                      ,(nreverse *loop-before-loop*)
811                      ,(nreverse *loop-body*)
812                      ,(nreverse *loop-after-body*)
813                      ,(nreconc *loop-epilogue*
814                                (nreverse *loop-after-epilogue*)))))
815       (dolist (entry *loop-bind-stack*)
816         (let ((vars (first entry))
817               (dcls (second entry))
818               (crocks (third entry))
819               (wrappers (fourth entry)))
820           (dolist (w wrappers)
821             (setq answer (append w (list answer))))
822           (when (or vars dcls crocks)
823             (let ((forms (list answer)))
824               ;;(when crocks (push crocks forms))
825               (when dcls (push `(declare ,@dcls) forms))
826               (setq answer `(,(if vars 'let 'locally)
827                              ,vars
828                              ,@(loop-build-destructuring-bindings crocks
829                                                                   forms)))))))
830       (do () (nil)
831         (setq answer `(block ,(pop *loop-names*) ,answer))
832         (unless *loop-names* (return nil)))
833       answer)))
834
835 (defun loop-iteration-driver ()
836   (do ()
837       ((null *loop-source-code*))
838     (let ((keyword (car *loop-source-code*)) (tem nil))
839       (cond ((not (symbolp keyword))
840              (loop-error "~S found where LOOP keyword expected" keyword))
841             (t (setq *loop-source-context* *loop-source-code*)
842                (loop-pop-source)
843                (cond ((setq tem
844                             (loop-lookup-keyword keyword
845                                                  (loop-universe-keywords
846                                                   *loop-universe*)))
847                       ;; It's a "miscellaneous" toplevel LOOP keyword (DO,
848                       ;; COLLECT, NAMED, etc.)
849                       (apply (symbol-function (first tem)) (rest tem)))
850                      ((setq tem
851                             (loop-lookup-keyword keyword
852                                                  (loop-universe-iteration-keywords *loop-universe*)))
853                       (loop-hack-iteration tem))
854                      ((loop-tmember keyword '(and else))
855                       ;; The alternative is to ignore it, i.e. let it go
856                       ;; around to the next keyword...
857                       (loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
858                                   keyword
859                                   (car *loop-source-code*)
860                                   (cadr *loop-source-code*)))
861                      (t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
862 \f
863 (defun loop-pop-source ()
864   (if *loop-source-code*
865       (pop *loop-source-code*)
866       (loop-error "LOOP source code ran out when another token was expected.")))
867
868 (defun loop-get-form ()
869   (if *loop-source-code*
870       (loop-pop-source)
871       (loop-error "LOOP code ran out where a form was expected.")))
872
873 (defun loop-get-compound-form ()
874   (let ((form (loop-get-form)))
875     (unless (consp form)
876       (loop-error "A compound form was expected, but ~S found." form))
877     form))
878
879 (defun loop-get-progn ()
880   (do ((forms (list (loop-get-compound-form))
881               (cons (loop-get-compound-form) forms))
882        (nextform (car *loop-source-code*)
883                  (car *loop-source-code*)))
884       ((atom nextform)
885        (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
886
887 (defun loop-construct-return (form)
888   `(return-from ,(car *loop-names*) ,form))
889
890 (defun loop-pseudo-body (form)
891   (cond ((or *loop-emitted-body* *loop-inside-conditional*)
892          (push form *loop-body*))
893         (t (push form *loop-before-loop*) (push form *loop-after-body*))))
894
895 (defun loop-emit-body (form)
896   (setq *loop-emitted-body* t)
897   (loop-pseudo-body form))
898
899 (defun loop-emit-final-value (&optional (form nil form-supplied-p))
900   (when form-supplied-p
901     (push (loop-construct-return form) *loop-after-epilogue*))
902   (setq *loop-final-value-culprit* (car *loop-source-context*)))
903
904 (defun loop-disallow-conditional (&optional kwd)
905   (when *loop-inside-conditional*
906     (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
907
908 (defun loop-disallow-anonymous-collectors ()
909   (when (find-if-not 'loop-collector-name *loop-collection-cruft*)
910     (loop-error "This LOOP clause is not permitted with anonymous collectors.")))
911
912 (defun loop-disallow-aggregate-booleans ()
913   (when (loop-tmember *loop-final-value-culprit* '(always never thereis))
914     (loop-error "This anonymous collection LOOP clause is not permitted with aggregate booleans.")))
915 \f
916 ;;;; loop types
917
918 (defun loop-typed-init (data-type &optional step-var-p)
919   (when (and data-type (sb!xc:subtypep data-type 'number))
920     (let ((init (if step-var-p 1 0)))
921       (flet ((like (&rest types)
922                (coerce init (find-if (lambda (type)
923                                        (sb!xc:subtypep data-type type))
924                                      types))))
925         (cond ((sb!xc:subtypep data-type 'float)
926                (like 'single-float 'double-float
927                      'short-float 'long-float 'float))
928               ((sb!xc:subtypep data-type '(complex float))
929                (like '(complex single-float)
930                      '(complex double-float)
931                      '(complex short-float)
932                      '(complex long-float)
933                      '(complex float)))
934               (t
935                init))))))
936
937 (defun loop-optional-type (&optional variable)
938   ;; No variable specified implies that no destructuring is permissible.
939   (and *loop-source-code* ; Don't get confused by NILs..
940        (let ((z (car *loop-source-code*)))
941          (cond ((loop-tequal z 'of-type)
942                 ;; This is the syntactically unambigous form in that
943                 ;; the form of the type specifier does not matter.
944                 ;; Also, it is assumed that the type specifier is
945                 ;; unambiguously, and without need of translation, a
946                 ;; common lisp type specifier or pattern (matching the
947                 ;; variable) thereof.
948                 (loop-pop-source)
949                 (loop-pop-source))
950
951                ((symbolp z)
952                 ;; This is the (sort of) "old" syntax, even though we
953                 ;; didn't used to support all of these type symbols.
954                 (let ((type-spec (or (gethash z
955                                               (loop-universe-type-symbols
956                                                *loop-universe*))
957                                      (gethash (symbol-name z)
958                                               (loop-universe-type-keywords
959                                                *loop-universe*)))))
960                   (when type-spec
961                     (loop-pop-source)
962                     type-spec)))
963                (t
964                 ;; This is our sort-of old syntax. But this is only
965                 ;; valid for when we are destructuring, so we will be
966                 ;; compulsive (should we really be?) and require that
967                 ;; we in fact be doing variable destructuring here. We
968                 ;; must translate the old keyword pattern typespec
969                 ;; into a fully-specified pattern of real type
970                 ;; specifiers here.
971                 (if (consp variable)
972                     (unless (consp z)
973                      (loop-error
974                         "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
975                         z))
976                     (loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
977                 (loop-pop-source)
978                 (labels ((translate (k v)
979                            (cond ((null k) nil)
980                                  ((atom k)
981                                   (replicate
982                                     (or (gethash k
983                                                  (loop-universe-type-symbols
984                                                   *loop-universe*))
985                                         (gethash (symbol-name k)
986                                                  (loop-universe-type-keywords
987                                                   *loop-universe*))
988                                         (loop-error
989                                           "The destructuring type pattern ~S contains the unrecognized type keyword ~S."
990                                           z k))
991                                     v))
992                                  ((atom v)
993                                   (loop-error
994                                     "The destructuring type pattern ~S doesn't match the variable pattern ~S."
995                                     z variable))
996                                  (t (cons (translate (car k) (car v))
997                                           (translate (cdr k) (cdr v))))))
998                          (replicate (typ v)
999                            (if (atom v)
1000                                typ
1001                                (cons (replicate typ (car v))
1002                                      (replicate typ (cdr v))))))
1003                   (translate z variable)))))))
1004 \f
1005 ;;;; loop variables
1006
1007 (defun loop-bind-block ()
1008   (when (or *loop-vars* *loop-declarations* *loop-wrappers*)
1009     (push (list (nreverse *loop-vars*)
1010                 *loop-declarations*
1011                 *loop-desetq-crocks*
1012                 *loop-wrappers*)
1013           *loop-bind-stack*)
1014     (setq *loop-vars* nil
1015           *loop-declarations* nil
1016           *loop-desetq-crocks* nil
1017           *loop-wrappers* nil)))
1018
1019 (defun loop-var-p (name)
1020   (do ((entry *loop-bind-stack* (cdr entry)))
1021       (nil)
1022     (cond
1023       ((null entry) (return nil))
1024       ((assoc name (caar entry) :test #'eq) (return t)))))
1025
1026 (defun loop-make-var (name initialization dtype &optional step-var-p)
1027   (cond ((null name)
1028          (setq name (gensym "LOOP-IGNORE-"))
1029          (push (list name initialization) *loop-vars*)
1030          (if (null initialization)
1031              (push `(ignore ,name) *loop-declarations*)
1032              (loop-declare-var name dtype)))
1033         ((atom name)
1034          (when (or (assoc name *loop-vars*)
1035                    (loop-var-p name))
1036            (loop-error "duplicated variable ~S in a LOOP binding" name))
1037          (unless (symbolp name)
1038            (loop-error "bad variable ~S somewhere in LOOP" name))
1039          (loop-declare-var name dtype step-var-p)
1040          ;; We use ASSOC on this list to check for duplications (above),
1041          ;; so don't optimize out this list:
1042          (push (list name (or initialization (loop-typed-init dtype step-var-p)))
1043                *loop-vars*))
1044         (initialization
1045          (let ((newvar (gensym "LOOP-DESTRUCTURE-")))
1046            (loop-declare-var name dtype)
1047            (push (list newvar initialization) *loop-vars*)
1048            ;; *LOOP-DESETQ-CROCKS* gathered in reverse order.
1049            (setq *loop-desetq-crocks*
1050                  (list* name newvar *loop-desetq-crocks*))))
1051         (t (let ((tcar nil) (tcdr nil))
1052              (if (atom dtype) (setq tcar (setq tcdr dtype))
1053                  (setq tcar (car dtype) tcdr (cdr dtype)))
1054              (loop-make-var (car name) nil tcar)
1055              (loop-make-var (cdr name) nil tcdr))))
1056   name)
1057
1058 (defun loop-declare-var (name dtype &optional step-var-p)
1059   (cond ((or (null name) (null dtype) (eq dtype t)) nil)
1060         ((symbolp name)
1061          (unless (or (sb!xc:subtypep t dtype)
1062                      (and (eq (find-package :cl) (symbol-package name))
1063                           (eq :special (sb!int:info :variable :kind name))))
1064            (let ((dtype (let ((init (loop-typed-init dtype step-var-p)))
1065                           (if (sb!xc:typep init dtype)
1066                               dtype
1067                               `(or (member ,init) ,dtype)))))
1068              (push `(type ,dtype ,name) *loop-declarations*))))
1069         ((consp name)
1070          (cond ((consp dtype)
1071                 (loop-declare-var (car name) (car dtype))
1072                 (loop-declare-var (cdr name) (cdr dtype)))
1073                (t (loop-declare-var (car name) dtype)
1074                   (loop-declare-var (cdr name) dtype))))
1075         (t (error "invalid LOOP variable passed in: ~S" name))))
1076
1077 (defun loop-maybe-bind-form (form data-type)
1078   (if (constantp form)
1079       form
1080       (loop-make-var (gensym "LOOP-BIND-") form data-type)))
1081 \f
1082 (defun loop-do-if (for negatep)
1083   (let ((form (loop-get-form))
1084         (*loop-inside-conditional* t)
1085         (it-p nil)
1086         (first-clause-p t))
1087     (flet ((get-clause (for)
1088              (do ((body nil)) (nil)
1089                (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
1090                  (cond ((not (symbolp key))
1091                         (loop-error
1092                           "~S found where keyword expected getting LOOP clause after ~S"
1093                           key for))
1094                        (t (setq *loop-source-context* *loop-source-code*)
1095                           (loop-pop-source)
1096                           (when (and (loop-tequal (car *loop-source-code*) 'it)
1097                                      first-clause-p)
1098                             (setq *loop-source-code*
1099                                   (cons (or it-p
1100                                             (setq it-p
1101                                                   (loop-when-it-var)))
1102                                         (cdr *loop-source-code*))))
1103                           (cond ((or (not (setq data (loop-lookup-keyword
1104                                                        key (loop-universe-keywords *loop-universe*))))
1105                                      (progn (apply (symbol-function (car data))
1106                                                    (cdr data))
1107                                             (null *loop-body*)))
1108                                  (loop-error
1109                                    "~S does not introduce a LOOP clause that can follow ~S."
1110                                    key for))
1111                                 (t (setq body (nreconc *loop-body* body)))))))
1112                (setq first-clause-p nil)
1113                (if (loop-tequal (car *loop-source-code*) :and)
1114                    (loop-pop-source)
1115                    (return (if (cdr body)
1116                                `(progn ,@(nreverse body))
1117                                (car body)))))))
1118       (let ((then (get-clause for))
1119             (else (when (loop-tequal (car *loop-source-code*) :else)
1120                     (loop-pop-source)
1121                     (list (get-clause :else)))))
1122         (when (loop-tequal (car *loop-source-code*) :end)
1123           (loop-pop-source))
1124         (when it-p (setq form `(setq ,it-p ,form)))
1125         (loop-pseudo-body
1126           `(if ,(if negatep `(not ,form) form)
1127                ,then
1128                ,@else))))))
1129
1130 (defun loop-do-initially ()
1131   (loop-disallow-conditional :initially)
1132   (push (loop-get-progn) *loop-prologue*))
1133
1134 (defun loop-do-finally ()
1135   (loop-disallow-conditional :finally)
1136   (push (loop-get-progn) *loop-epilogue*))
1137
1138 (defun loop-do-do ()
1139   (loop-emit-body (loop-get-progn)))
1140
1141 (defun loop-do-named ()
1142   (let ((name (loop-pop-source)))
1143     (unless (symbolp name)
1144       (loop-error "~S is an invalid name for your LOOP" name))
1145     (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1146       (loop-error "The NAMED ~S clause occurs too late." name))
1147     (when *loop-names*
1148       (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1149                   (car *loop-names*) name))
1150     (setq *loop-names* (list name))))
1151
1152 (defun loop-do-return ()
1153   (loop-emit-body (loop-construct-return (loop-get-form))))
1154 \f
1155 ;;;; value accumulation: LIST
1156
1157 (defstruct (loop-collector
1158             (:copier nil)
1159             (:predicate nil))
1160   name
1161   class
1162   (history nil)
1163   (tempvars nil)
1164   dtype
1165   (data nil)) ;collector-specific data
1166
1167 (defun loop-get-collection-info (collector class default-type)
1168   (let ((form (loop-get-form))
1169         (dtype (and (not (loop-universe-ansi *loop-universe*)) (loop-optional-type)))
1170         (name (when (loop-tequal (car *loop-source-code*) 'into)
1171                 (loop-pop-source)
1172                 (loop-pop-source))))
1173     (when (not (symbolp name))
1174       (loop-error "The value accumulation recipient name, ~S, is not a symbol." name))
1175     (unless name
1176       (loop-disallow-aggregate-booleans))
1177     (unless dtype
1178       (setq dtype (or (loop-optional-type) default-type)))
1179     (let ((cruft (find (the symbol name) *loop-collection-cruft*
1180                        :key #'loop-collector-name)))
1181       (cond ((not cruft)
1182              (when (and name (loop-var-p name))
1183                (loop-error "Variable ~S in INTO clause is a duplicate" name))
1184              (push (setq cruft (make-loop-collector
1185                                  :name name :class class
1186                                  :history (list collector) :dtype dtype))
1187                    *loop-collection-cruft*))
1188             (t (unless (eq (loop-collector-class cruft) class)
1189                  (loop-error
1190                    "incompatible kinds of LOOP value accumulation specified for collecting~@
1191                     ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S"
1192                    name (car (loop-collector-history cruft)) collector))
1193                (unless (equal dtype (loop-collector-dtype cruft))
1194                  (loop-warn
1195                    "unequal datatypes specified in different LOOP value accumulations~@
1196                    into ~S: ~S and ~S"
1197                    name dtype (loop-collector-dtype cruft))
1198                  (when (eq (loop-collector-dtype cruft) t)
1199                    (setf (loop-collector-dtype cruft) dtype)))
1200                (push collector (loop-collector-history cruft))))
1201       (values cruft form))))
1202
1203 (defun loop-list-collection (specifically)      ; NCONC, LIST, or APPEND
1204   (multiple-value-bind (lc form)
1205       (loop-get-collection-info specifically 'list 'list)
1206     (let ((tempvars (loop-collector-tempvars lc)))
1207       (unless tempvars
1208         (setf (loop-collector-tempvars lc)
1209               (setq tempvars (list* (gensym "LOOP-LIST-HEAD-")
1210                                     (gensym "LOOP-LIST-TAIL-")
1211                                     (and (loop-collector-name lc)
1212                                          (list (loop-collector-name lc))))))
1213         (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1214         (unless (loop-collector-name lc)
1215           (loop-emit-final-value `(loop-collect-answer ,(car tempvars)
1216                                                        ,@(cddr tempvars)))))
1217       (ecase specifically
1218         (list (setq form `(list ,form)))
1219         (nconc nil)
1220         (append (unless (and (consp form) (eq (car form) 'list))
1221                   (setq form `(copy-list ,form)))))
1222       (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1223 \f
1224 ;;;; value accumulation: MAX, MIN, SUM, COUNT
1225
1226 (defun loop-sum-collection (specifically required-type default-type);SUM, COUNT
1227   (multiple-value-bind (lc form)
1228       (loop-get-collection-info specifically 'sum default-type)
1229     (loop-check-data-type (loop-collector-dtype lc) required-type)
1230     (let ((tempvars (loop-collector-tempvars lc)))
1231       (unless tempvars
1232         (setf (loop-collector-tempvars lc)
1233               (setq tempvars (list (loop-make-var
1234                                      (or (loop-collector-name lc)
1235                                          (gensym "LOOP-SUM-"))
1236                                      nil (loop-collector-dtype lc)))))
1237         (unless (loop-collector-name lc)
1238           (loop-emit-final-value (car (loop-collector-tempvars lc)))))
1239       (loop-emit-body
1240         (if (eq specifically 'count)
1241             `(when ,form
1242                (setq ,(car tempvars)
1243                      (1+ ,(car tempvars))))
1244             `(setq ,(car tempvars)
1245                    (+ ,(car tempvars)
1246                       ,form)))))))
1247
1248 (defun loop-maxmin-collection (specifically)
1249   (multiple-value-bind (lc form)
1250       (loop-get-collection-info specifically 'maxmin 'real)
1251     (loop-check-data-type (loop-collector-dtype lc) 'real)
1252     (let ((data (loop-collector-data lc)))
1253       (unless data
1254         (setf (loop-collector-data lc)
1255               (setq data (make-loop-minimax
1256                            (or (loop-collector-name lc)
1257                                (gensym "LOOP-MAXMIN-"))
1258                            (loop-collector-dtype lc))))
1259         (unless (loop-collector-name lc)
1260           (loop-emit-final-value (loop-minimax-answer-variable data))))
1261       (loop-note-minimax-operation specifically data)
1262       (push `(with-minimax-value ,data) *loop-wrappers*)
1263       (loop-emit-body `(loop-accumulate-minimax-value ,data
1264                                                       ,specifically
1265                                                       ,form)))))
1266 \f
1267 ;;;; value accumulation: aggregate booleans
1268
1269 ;;; handling the ALWAYS and NEVER loop keywords
1270 ;;;
1271 ;;; Under ANSI these are not permitted to appear under conditionalization.
1272 (defun loop-do-always (restrictive negate)
1273   (let ((form (loop-get-form)))
1274     (when restrictive (loop-disallow-conditional))
1275     (loop-disallow-anonymous-collectors)
1276     (loop-emit-body `(,(if negate 'when 'unless) ,form
1277                       ,(loop-construct-return nil)))
1278     (loop-emit-final-value t)))
1279
1280 ;;; handling the THEREIS loop keyword
1281 ;;;
1282 ;;; Under ANSI this is not permitted to appear under conditionalization.
1283 (defun loop-do-thereis (restrictive)
1284   (when restrictive (loop-disallow-conditional))
1285   (loop-disallow-anonymous-collectors)
1286   (loop-emit-final-value)
1287   (loop-emit-body `(when (setq ,(loop-when-it-var) ,(loop-get-form))
1288                     ,(loop-construct-return *loop-when-it-var*))))
1289 \f
1290 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1291   (loop-disallow-conditional kwd)
1292   (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1293
1294 (defun loop-do-repeat ()
1295   (loop-disallow-conditional :repeat)
1296   (let ((form (loop-get-form))
1297         (type 'integer))
1298     (let ((var (loop-make-var (gensym "LOOP-REPEAT-") `(ceiling ,form) type)))
1299       (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-before-loop*)
1300       (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-after-body*)
1301       ;; FIXME: What should
1302       ;;   (loop count t into a
1303       ;;         repeat 3
1304       ;;         count t into b
1305       ;;         finally (return (list a b)))
1306       ;; return: (3 3) or (4 3)? PUSHes above are for the former
1307       ;; variant, L-P-B below for the latter.
1308       #+nil (loop-pseudo-body `(when (minusp (decf ,var)) (go end-loop))))))
1309
1310 (defun loop-do-with ()
1311   (loop-disallow-conditional :with)
1312   (do ((var) (val) (dtype))
1313       (nil)
1314     (setq var (loop-pop-source)
1315           dtype (loop-optional-type var)
1316           val (cond ((loop-tequal (car *loop-source-code*) :=)
1317                      (loop-pop-source)
1318                      (loop-get-form))
1319                     (t nil)))
1320     (when (and var (loop-var-p var))
1321       (loop-error "Variable ~S has already been used" var))
1322     (loop-make-var var val dtype)
1323     (if (loop-tequal (car *loop-source-code*) :and)
1324         (loop-pop-source)
1325         (return (loop-bind-block)))))
1326 \f
1327 ;;;; the iteration driver
1328
1329 (defun loop-hack-iteration (entry)
1330   (flet ((make-endtest (list-of-forms)
1331            (cond ((null list-of-forms) nil)
1332                  ((member t list-of-forms) '(go end-loop))
1333                  (t `(when ,(if (null (cdr (setq list-of-forms
1334                                                  (nreverse list-of-forms))))
1335                                 (car list-of-forms)
1336                                 (cons 'or list-of-forms))
1337                        (go end-loop))))))
1338     (do ((pre-step-tests nil)
1339          (steps nil)
1340          (post-step-tests nil)
1341          (pseudo-steps nil)
1342          (pre-loop-pre-step-tests nil)
1343          (pre-loop-steps nil)
1344          (pre-loop-post-step-tests nil)
1345          (pre-loop-pseudo-steps nil)
1346          (tem) (data))
1347         (nil)
1348       ;; Note that we collect endtests in reverse order, but steps in correct
1349       ;; order. MAKE-ENDTEST does the nreverse for us.
1350       (setq tem (setq data
1351                       (apply (symbol-function (first entry)) (rest entry))))
1352       (and (car tem) (push (car tem) pre-step-tests))
1353       (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1354       (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1355       (setq pseudo-steps
1356             (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1357       (setq tem (cdr tem))
1358       (when *loop-emitted-body*
1359         (loop-error "iteration in LOOP follows body code"))
1360       (unless tem (setq tem data))
1361       (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1362       ;; FIXME: This (SETF FOO (NCONC FOO BAR)) idiom appears often enough
1363       ;; that it might be worth making it into an NCONCF macro.
1364       (setq pre-loop-steps
1365             (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1366       (when (car (setq tem (cdr tem)))
1367         (push (car tem) pre-loop-post-step-tests))
1368       (setq pre-loop-pseudo-steps
1369             (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1370       (unless (loop-tequal (car *loop-source-code*) :and)
1371         (setq *loop-before-loop*
1372               (list* (loop-make-desetq pre-loop-pseudo-steps)
1373                      (make-endtest pre-loop-post-step-tests)
1374                      (loop-make-psetq pre-loop-steps)
1375                      (make-endtest pre-loop-pre-step-tests)
1376                      *loop-before-loop*))
1377         (setq *loop-after-body*
1378               (list* (loop-make-desetq pseudo-steps)
1379                      (make-endtest post-step-tests)
1380                      (loop-make-psetq steps)
1381                      (make-endtest pre-step-tests)
1382                      *loop-after-body*))
1383         (loop-bind-block)
1384         (return nil))
1385       (loop-pop-source)                         ; Flush the "AND".
1386       (when (and (not (loop-universe-implicit-for-required *loop-universe*))
1387                  (setq tem
1388                        (loop-lookup-keyword
1389                         (car *loop-source-code*)
1390                         (loop-universe-iteration-keywords *loop-universe*))))
1391         ;; The latest ANSI clarification is that the FOR/AS after the AND must
1392         ;; NOT be supplied.
1393         (loop-pop-source)
1394         (setq entry tem)))))
1395 \f
1396 ;;;; main iteration drivers
1397
1398 ;;; FOR variable keyword ..args..
1399 (defun loop-do-for ()
1400   (let* ((var (loop-pop-source))
1401          (data-type (loop-optional-type var))
1402          (keyword (loop-pop-source))
1403          (first-arg nil)
1404          (tem nil))
1405     (setq first-arg (loop-get-form))
1406     (unless (and (symbolp keyword)
1407                  (setq tem (loop-lookup-keyword
1408                              keyword
1409                              (loop-universe-for-keywords *loop-universe*))))
1410       (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP."
1411                   keyword))
1412     (apply (car tem) var first-arg data-type (cdr tem))))
1413
1414 (defun loop-when-it-var ()
1415   (or *loop-when-it-var*
1416       (setq *loop-when-it-var*
1417             (loop-make-var (gensym "LOOP-IT-") nil nil))))
1418 \f
1419 ;;;; various FOR/AS subdispatches
1420
1421 ;;; ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when
1422 ;;; the THEN is omitted (other than being more stringent in its
1423 ;;; placement), and like the old "FOR x FIRST y THEN z" when the THEN
1424 ;;; is present. I.e., the first initialization occurs in the loop body
1425 ;;; (first-step), not in the variable binding phase.
1426 (defun loop-ansi-for-equals (var val data-type)
1427   (loop-make-var var nil data-type)
1428   (cond ((loop-tequal (car *loop-source-code*) :then)
1429          ;; Then we are the same as "FOR x FIRST y THEN z".
1430          (loop-pop-source)
1431          `(() (,var ,(loop-get-form)) () ()
1432            () (,var ,val) () ()))
1433         (t ;; We are the same as "FOR x = y".
1434          `(() (,var ,val) () ()))))
1435
1436 (defun loop-for-across (var val data-type)
1437   (loop-make-var var nil data-type)
1438   (let ((vector-var (gensym "LOOP-ACROSS-VECTOR-"))
1439         (index-var (gensym "LOOP-ACROSS-INDEX-")))
1440     (multiple-value-bind (vector-form constantp vector-value)
1441         (loop-constant-fold-if-possible val 'vector)
1442       (loop-make-var
1443         vector-var vector-form
1444         (if (and (consp vector-form) (eq (car vector-form) 'the))
1445             (cadr vector-form)
1446             'vector))
1447       (loop-make-var index-var 0 'fixnum)
1448       (let* ((length 0)
1449              (length-form (cond ((not constantp)
1450                                  (let ((v (gensym "LOOP-ACROSS-LIMIT-")))
1451                                    (push `(setq ,v (length ,vector-var))
1452                                          *loop-prologue*)
1453                                    (loop-make-var v 0 'fixnum)))
1454                                 (t (setq length (length vector-value)))))
1455              (first-test `(>= ,index-var ,length-form))
1456              (other-test first-test)
1457              (step `(,var (aref ,vector-var ,index-var)))
1458              (pstep `(,index-var (1+ ,index-var))))
1459         (declare (fixnum length))
1460         (when constantp
1461           (setq first-test (= length 0))
1462           (when (<= length 1)
1463             (setq other-test t)))
1464         `(,other-test ,step () ,pstep
1465           ,@(and (not (eq first-test other-test))
1466                  `(,first-test ,step () ,pstep)))))))
1467 \f
1468 ;;;; list iteration
1469
1470 (defun loop-list-step (listvar)
1471   ;; We are not equipped to analyze whether 'FOO is the same as #'FOO
1472   ;; here in any sensible fashion, so let's give an obnoxious warning
1473   ;; whenever 'FOO is used as the stepping function.
1474   ;;
1475   ;; While a Discerning Compiler may deal intelligently with
1476   ;; (FUNCALL 'FOO ...), not recognizing FOO may defeat some LOOP
1477   ;; optimizations.
1478   (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1479                         (loop-pop-source)
1480                         (loop-get-form))
1481                        (t '(function cdr)))))
1482     (cond ((and (consp stepper) (eq (car stepper) 'quote))
1483            (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1484            `(funcall ,stepper ,listvar))
1485           ((and (consp stepper) (eq (car stepper) 'function))
1486            (list (cadr stepper) listvar))
1487           (t
1488            `(funcall ,(loop-make-var (gensym "LOOP-FN-") stepper 'function)
1489                      ,listvar)))))
1490
1491 (defun loop-for-on (var val data-type)
1492   (multiple-value-bind (list constantp list-value)
1493       (loop-constant-fold-if-possible val)
1494     (let ((listvar var))
1495       (cond ((and var (symbolp var))
1496              (loop-make-var var list data-type))
1497             (t
1498              (loop-make-var (setq listvar (gensym)) list 't)
1499              (loop-make-var var nil data-type)))
1500       (let ((list-step (loop-list-step listvar)))
1501         (let* ((first-endtest
1502                 ;; mysterious comment from original CMU CL sources:
1503                 ;;   the following should use `atom' instead of `endp',
1504                 ;;   per [bug2428]
1505                 `(atom ,listvar))
1506                (other-endtest first-endtest))
1507           (when (and constantp (listp list-value))
1508             (setq first-endtest (null list-value)))
1509           (cond ((eq var listvar)
1510                  ;; The contour of the loop is different because we
1511                  ;; use the user's variable...
1512                  `(() (,listvar ,list-step)
1513                    ,other-endtest () () () ,first-endtest ()))
1514                 (t (let ((step `(,var ,listvar))
1515                          (pseudo `(,listvar ,list-step)))
1516                      `(,other-endtest ,step () ,pseudo
1517                        ,@(and (not (eq first-endtest other-endtest))
1518                               `(,first-endtest ,step () ,pseudo)))))))))))
1519
1520 (defun loop-for-in (var val data-type)
1521   (multiple-value-bind (list constantp list-value)
1522       (loop-constant-fold-if-possible val)
1523     (let ((listvar (gensym "LOOP-LIST-")))
1524       (loop-make-var var nil data-type)
1525       (loop-make-var listvar list 'list)
1526       (let ((list-step (loop-list-step listvar)))
1527         (let* ((first-endtest `(endp ,listvar))
1528                (other-endtest first-endtest)
1529                (step `(,var (car ,listvar)))
1530                (pseudo-step `(,listvar ,list-step)))
1531           (when (and constantp (listp list-value))
1532             (setq first-endtest (null list-value)))
1533           `(,other-endtest ,step () ,pseudo-step
1534             ,@(and (not (eq first-endtest other-endtest))
1535                    `(,first-endtest ,step () ,pseudo-step))))))))
1536 \f
1537 ;;;; iteration paths
1538
1539 (defstruct (loop-path
1540             (:copier nil)
1541             (:predicate nil))
1542   names
1543   preposition-groups
1544   inclusive-permitted
1545   function
1546   user-data)
1547
1548 (defun add-loop-path (names function universe
1549                       &key preposition-groups inclusive-permitted user-data)
1550   (declare (type loop-universe universe))
1551   (unless (listp names)
1552     (setq names (list names)))
1553   (let ((ht (loop-universe-path-keywords universe))
1554         (lp (make-loop-path
1555               :names (mapcar #'symbol-name names)
1556               :function function
1557               :user-data user-data
1558               :preposition-groups (mapcar (lambda (x)
1559                                             (if (listp x) x (list x)))
1560                                           preposition-groups)
1561               :inclusive-permitted inclusive-permitted)))
1562     (dolist (name names)
1563       (setf (gethash (symbol-name name) ht) lp))
1564     lp))
1565 \f
1566 ;;; Note: Path functions are allowed to use LOOP-MAKE-VAR, hack
1567 ;;; the prologue, etc.
1568 (defun loop-for-being (var val data-type)
1569   ;; FOR var BEING each/the pathname prep-phrases using-stuff... each/the =
1570   ;; EACH or THE. Not clear if it is optional, so I guess we'll warn.
1571   (let ((path nil)
1572         (data nil)
1573         (inclusive nil)
1574         (stuff nil)
1575         (initial-prepositions nil))
1576     (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1577           ((loop-tequal (car *loop-source-code*) :and)
1578            (loop-pop-source)
1579            (setq inclusive t)
1580            (unless (loop-tmember (car *loop-source-code*)
1581                                  '(:its :each :his :her))
1582              (loop-error "~S was found where ITS or EACH expected in LOOP iteration path syntax."
1583                          (car *loop-source-code*)))
1584            (loop-pop-source)
1585            (setq path (loop-pop-source))
1586            (setq initial-prepositions `((:in ,val))))
1587           (t (loop-error "unrecognizable LOOP iteration path syntax: missing EACH or THE?")))
1588     (cond ((not (symbolp path))
1589            (loop-error
1590             "~S was found where a LOOP iteration path name was expected."
1591             path))
1592           ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1593            (loop-error "~S is not the name of a LOOP iteration path." path))
1594           ((and inclusive (not (loop-path-inclusive-permitted data)))
1595            (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1596     (let ((fun (loop-path-function data))
1597           (preps (nconc initial-prepositions
1598                         (loop-collect-prepositional-phrases
1599                          (loop-path-preposition-groups data)
1600                          t)))
1601           (user-data (loop-path-user-data data)))
1602       (when (symbolp fun) (setq fun (symbol-function fun)))
1603       (setq stuff (if inclusive
1604                       (apply fun var data-type preps :inclusive t user-data)
1605                       (apply fun var data-type preps user-data))))
1606     (when *loop-named-vars*
1607       (loop-error "Unused USING vars: ~S." *loop-named-vars*))
1608     ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back).
1609     ;; Protect the system from the user and the user from himself.
1610     (unless (member (length stuff) '(6 10))
1611       (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1612                   path))
1613     (do ((l (car stuff) (cdr l)) (x)) ((null l))
1614       (if (atom (setq x (car l)))
1615           (loop-make-var x nil nil)
1616           (loop-make-var (car x) (cadr x) (caddr x))))
1617     (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1618     (cddr stuff)))
1619 \f
1620 (defun loop-named-var (name)
1621   (let ((tem (loop-tassoc name *loop-named-vars*)))
1622     (declare (list tem))
1623     (cond ((null tem) (values (gensym) nil))
1624           (t (setq *loop-named-vars* (delete tem *loop-named-vars*))
1625              (values (cdr tem) t)))))
1626
1627 (defun loop-collect-prepositional-phrases (preposition-groups
1628                                            &optional
1629                                            using-allowed
1630                                            initial-phrases)
1631   (flet ((in-group-p (x group) (car (loop-tmember x group))))
1632     (do ((token nil)
1633          (prepositional-phrases initial-phrases)
1634          (this-group nil nil)
1635          (this-prep nil nil)
1636          (disallowed-prepositions
1637            (mapcan (lambda (x)
1638                      (copy-list
1639                       (find (car x) preposition-groups :test #'in-group-p)))
1640                    initial-phrases))
1641          (used-prepositions (mapcar #'car initial-phrases)))
1642         ((null *loop-source-code*) (nreverse prepositional-phrases))
1643       (declare (symbol this-prep))
1644       (setq token (car *loop-source-code*))
1645       (dolist (group preposition-groups)
1646         (when (setq this-prep (in-group-p token group))
1647           (return (setq this-group group))))
1648       (cond (this-group
1649              (when (member this-prep disallowed-prepositions)
1650                (loop-error
1651                  (if (member this-prep used-prepositions)
1652                      "A ~S prepositional phrase occurs multiply for some LOOP clause."
1653                      "Preposition ~S was used when some other preposition has subsumed it.")
1654                  token))
1655              (setq used-prepositions (if (listp this-group)
1656                                          (append this-group used-prepositions)
1657                                          (cons this-group used-prepositions)))
1658              (loop-pop-source)
1659              (push (list this-prep (loop-get-form)) prepositional-phrases))
1660             ((and using-allowed (loop-tequal token 'using))
1661              (loop-pop-source)
1662              (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1663                (when (cadr z)
1664                  (if (setq tem (loop-tassoc (car z) *loop-named-vars*))
1665                      (loop-error
1666                        "The variable substitution for ~S occurs twice in a USING phrase,~@
1667                         with ~S and ~S."
1668                        (car z) (cadr z) (cadr tem))
1669                      (push (cons (car z) (cadr z)) *loop-named-vars*)))
1670                (when (or (null *loop-source-code*)
1671                          (symbolp (car *loop-source-code*)))
1672                  (return nil))))
1673             (t (return (nreverse prepositional-phrases)))))))
1674 \f
1675 ;;;; master sequencer function
1676
1677 (defun loop-sequencer (indexv indexv-type
1678                        variable variable-type
1679                        sequence-variable sequence-type
1680                        step-hack default-top
1681                        prep-phrases)
1682    (let ((endform nil) ; form (constant or variable) with limit value
1683          (sequencep nil) ; T if sequence arg has been provided
1684          (testfn nil) ; endtest function
1685          (test nil) ; endtest form
1686          (stepby (1+ (or (loop-typed-init indexv-type) 0))) ; our increment
1687          (stepby-constantp t)
1688          (step nil) ; step form
1689          (dir nil) ; direction of stepping: NIL, :UP, :DOWN
1690          (inclusive-iteration nil) ; T if include last index
1691          (start-given nil) ; T when prep phrase has specified start
1692          (start-value nil)
1693          (start-constantp nil)
1694          (limit-given nil) ; T when prep phrase has specified end
1695          (limit-constantp nil)
1696          (limit-value nil)
1697          )
1698      (flet ((assert-index-for-arithmetic (index)
1699               (unless (atom index)
1700                 (loop-error "Arithmetic index must be an atom."))))
1701        (when variable (loop-make-var variable nil variable-type))
1702        (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1703          (setq prep (caar l) form (cadar l))
1704          (case prep
1705            ((:of :in)
1706             (setq sequencep t)
1707             (loop-make-var sequence-variable form sequence-type))
1708            ((:from :downfrom :upfrom)
1709             (setq start-given t)
1710             (cond ((eq prep :downfrom) (setq dir ':down))
1711                   ((eq prep :upfrom) (setq dir ':up)))
1712             (multiple-value-setq (form start-constantp start-value)
1713               (loop-constant-fold-if-possible form indexv-type))
1714             (assert-index-for-arithmetic indexv)
1715             ;; KLUDGE: loop-make-var generates a temporary symbol for
1716             ;; indexv if it is NIL. We have to use it to have the index
1717             ;; actually count
1718             (setq indexv (loop-make-var indexv form indexv-type)))
1719            ((:upto :to :downto :above :below)
1720             (cond ((loop-tequal prep :upto) (setq inclusive-iteration
1721                                                   (setq dir ':up)))
1722                   ((loop-tequal prep :to) (setq inclusive-iteration t))
1723                   ((loop-tequal prep :downto) (setq inclusive-iteration
1724                                                     (setq dir ':down)))
1725                   ((loop-tequal prep :above) (setq dir ':down))
1726                   ((loop-tequal prep :below) (setq dir ':up)))
1727             (setq limit-given t)
1728             (multiple-value-setq (form limit-constantp limit-value)
1729               (loop-constant-fold-if-possible form `(and ,indexv-type real)))
1730             (setq endform (if limit-constantp
1731                               `',limit-value
1732                               (loop-make-var
1733                                  (gensym "LOOP-LIMIT-") form
1734                                  `(and ,indexv-type real)))))
1735            (:by
1736             (multiple-value-setq (form stepby-constantp stepby)
1737               (loop-constant-fold-if-possible form
1738                                               `(and ,indexv-type (real (0)))))
1739             (unless stepby-constantp
1740               (loop-make-var (setq stepby (gensym "LOOP-STEP-BY-"))
1741                  form
1742                  `(and ,indexv-type (real (0)))
1743                  t)))
1744            (t (loop-error
1745                  "~S invalid preposition in sequencing or sequence path;~@
1746               maybe invalid prepositions were specified in iteration path descriptor?"
1747                  prep)))
1748          (when (and odir dir (not (eq dir odir)))
1749            (loop-error
1750              "conflicting stepping directions in LOOP sequencing path"))
1751          (setq odir dir))
1752        (when (and sequence-variable (not sequencep))
1753          (loop-error "missing OF or IN phrase in sequence path"))
1754        ;; Now fill in the defaults.
1755        (if start-given
1756            (when limit-given
1757              ;; if both start and limit are given, they had better both
1758              ;; be REAL.  We already enforce the REALness of LIMIT,
1759              ;; above; here's the KLUDGE to enforce the type of START.
1760              (flet ((type-declaration-of (x)
1761                       (and (eq (car x) 'type) (caddr x))))
1762                (let ((decl (find indexv *loop-declarations*
1763                                  :key #'type-declaration-of))
1764                      (%decl (find indexv *loop-declarations*
1765                                   :key #'type-declaration-of
1766                                   :from-end t)))
1767                  (sb!int:aver (eq decl %decl))
1768                  (when decl
1769                    (setf (cadr decl)
1770                          `(and real ,(cadr decl)))))))
1771            ;; default start
1772            ;; DUPLICATE KLUDGE: loop-make-var generates a temporary
1773            ;; symbol for indexv if it is NIL. See also the comment in
1774            ;; the (:from :downfrom :upfrom) case
1775            (progn
1776              (assert-index-for-arithmetic indexv)
1777              (setq indexv
1778                    (loop-make-var
1779                       indexv
1780                       (setq start-constantp t
1781                             start-value (or (loop-typed-init indexv-type) 0))
1782                       `(and ,indexv-type real)))))
1783        (cond ((member dir '(nil :up))
1784               (when (or limit-given default-top)
1785                 (unless limit-given
1786                   (loop-make-var (setq endform (gensym "LOOP-SEQ-LIMIT-"))
1787                      nil
1788                      indexv-type)
1789                   (push `(setq ,endform ,default-top) *loop-prologue*))
1790                 (setq testfn (if inclusive-iteration '> '>=)))
1791               (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1792              (t (unless start-given
1793                   (unless default-top
1794                     (loop-error "don't know where to start stepping"))
1795                   (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1796                 (when (and default-top (not endform))
1797                   (setq endform (loop-typed-init indexv-type)
1798                         inclusive-iteration t))
1799                 (when endform (setq testfn (if inclusive-iteration  '< '<=)))
1800                 (setq step
1801                       (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1802        (when testfn
1803          (setq test
1804                `(,testfn ,indexv ,endform)))
1805        (when step-hack
1806          (setq step-hack
1807                `(,variable ,step-hack)))
1808        (let ((first-test test) (remaining-tests test))
1809          ;; As far as I can tell, the effect of the following code is
1810          ;; to detect cases where we know statically whether the first
1811          ;; iteration of the loop will be executed. Depending on the
1812          ;; situation, we can either:
1813          ;;  a) save one jump and one comparison per loop (not per iteration)
1814          ;;     when it will get executed
1815          ;;  b) remove the loop body completely when it won't be executed
1816          ;;
1817          ;; Noble goals. However, the code generated in case a) will
1818          ;; fool the loop induction variable detection, and cause
1819          ;; code like (LOOP FOR I TO 10 ...) to use generic addition
1820          ;; (bug #278a).
1821          ;;
1822          ;; Since the gain in case a) is rather minimal and Python is
1823          ;; generally smart enough to handle b) without any extra
1824          ;; support from the loop macro, I've disabled this code for
1825          ;; now. The code and the comment left here in case somebody
1826          ;; extends the induction variable bound detection to work
1827          ;; with code where the stepping precedes the test.
1828          ;; -- JES 2005-11-30
1829          #+nil
1830          (when (and stepby-constantp start-constantp limit-constantp
1831                     (realp start-value) (realp limit-value))
1832            (when (setq first-test
1833                        (funcall (symbol-function testfn)
1834                                 start-value
1835                                 limit-value))
1836              (setq remaining-tests t)))
1837          `(() (,indexv ,step)
1838            ,remaining-tests ,step-hack () () ,first-test ,step-hack)))))
1839 \f
1840 ;;;; interfaces to the master sequencer
1841
1842 (defun loop-for-arithmetic (var val data-type kwd)
1843   (loop-sequencer
1844    var (loop-check-data-type data-type 'number)
1845    nil nil nil nil nil nil
1846    (loop-collect-prepositional-phrases
1847     '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1848     nil (list (list kwd val)))))
1849
1850 \f
1851 ;;;; builtin LOOP iteration paths
1852
1853 #||
1854 (loop for v being the hash-values of ht do (print v))
1855 (loop for k being the hash-keys of ht do (print k))
1856 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1857 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1858 ||#
1859
1860 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
1861                                        &key (which (sb!int:missing-arg)))
1862   (declare (type (member :hash-key :hash-value) which))
1863   (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1864          (loop-error "too many prepositions!"))
1865         ((null prep-phrases)
1866          (loop-error "missing OF or IN in ~S iteration path")))
1867   (let ((ht-var (gensym "LOOP-HASHTAB-"))
1868         (next-fn (gensym "LOOP-HASHTAB-NEXT-"))
1869         (dummy-predicate-var nil)
1870         (post-steps nil))
1871     (multiple-value-bind (other-var other-p)
1872         (loop-named-var (ecase which
1873                           (:hash-key 'hash-value)
1874                           (:hash-value 'hash-key)))
1875       ;; @@@@ LOOP-NAMED-VAR returns a second value of T if the name
1876       ;; was actually specified, so clever code can throw away the
1877       ;; GENSYM'ed-up variable if it isn't really needed. The
1878       ;; following is for those implementations in which we cannot put
1879       ;; dummy NILs into MULTIPLE-VALUE-SETQ variable lists.
1880       (setq other-p t
1881             dummy-predicate-var (loop-when-it-var))
1882       (let* ((key-var nil)
1883              (val-var nil)
1884              (variable (or variable (gensym "LOOP-HASH-VAR-TEMP-")))
1885              (bindings `((,variable nil ,data-type)
1886                          (,ht-var ,(cadar prep-phrases))
1887                          ,@(and other-p other-var `((,other-var nil))))))
1888         (ecase which
1889           (:hash-key (setq key-var variable
1890                            val-var (and other-p other-var)))
1891           (:hash-value (setq key-var (and other-p other-var)
1892                              val-var variable)))
1893         (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1894         (when (or (consp key-var) data-type)
1895           (setq post-steps
1896                 `(,key-var ,(setq key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1897                            ,@post-steps))
1898           (push `(,key-var nil) bindings))
1899         (when (or (consp val-var) data-type)
1900           (setq post-steps
1901                 `(,val-var ,(setq val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1902                            ,@post-steps))
1903           (push `(,val-var nil) bindings))
1904         `(,bindings                     ;bindings
1905           ()                            ;prologue
1906           ()                            ;pre-test
1907           ()                            ;parallel steps
1908           (not (multiple-value-setq (,dummy-predicate-var ,key-var ,val-var)
1909                  (,next-fn)))           ;post-test
1910           ,post-steps)))))
1911
1912 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
1913                                             &key symbol-types)
1914   (cond ((and prep-phrases (cdr prep-phrases))
1915          (loop-error "Too many prepositions!"))
1916         ((and prep-phrases (not (member (caar prep-phrases) '(:in :of))))
1917          (sb!int:bug "Unknown preposition ~S." (caar prep-phrases))))
1918   (unless (symbolp variable)
1919     (loop-error "Destructuring is not valid for package symbol iteration."))
1920   (let ((pkg-var (gensym "LOOP-PKGSYM-"))
1921         (next-fn (gensym "LOOP-PKGSYM-NEXT-"))
1922         (variable (or variable (gensym "LOOP-PKGSYM-VAR-")))
1923         (package (or (cadar prep-phrases) '*package*)))
1924     (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types))
1925           *loop-wrappers*)
1926     `(((,variable nil ,data-type) (,pkg-var ,package))
1927       ()
1928       ()
1929       ()
1930       (not (multiple-value-setq (,(loop-when-it-var)
1931                                  ,variable)
1932              (,next-fn)))
1933       ())))
1934 \f
1935 ;;;; ANSI LOOP
1936
1937 (defun make-ansi-loop-universe (extended-p)
1938   (let ((w (make-standard-loop-universe
1939              :keywords '((named (loop-do-named))
1940                          (initially (loop-do-initially))
1941                          (finally (loop-do-finally))
1942                          (do (loop-do-do))
1943                          (doing (loop-do-do))
1944                          (return (loop-do-return))
1945                          (collect (loop-list-collection list))
1946                          (collecting (loop-list-collection list))
1947                          (append (loop-list-collection append))
1948                          (appending (loop-list-collection append))
1949                          (nconc (loop-list-collection nconc))
1950                          (nconcing (loop-list-collection nconc))
1951                          (count (loop-sum-collection count
1952                                                      real
1953                                                      fixnum))
1954                          (counting (loop-sum-collection count
1955                                                         real
1956                                                         fixnum))
1957                          (sum (loop-sum-collection sum number number))
1958                          (summing (loop-sum-collection sum number number))
1959                          (maximize (loop-maxmin-collection max))
1960                          (minimize (loop-maxmin-collection min))
1961                          (maximizing (loop-maxmin-collection max))
1962                          (minimizing (loop-maxmin-collection min))
1963                          (always (loop-do-always t nil)) ; Normal, do always
1964                          (never (loop-do-always t t)) ; Negate test on always.
1965                          (thereis (loop-do-thereis t))
1966                          (while (loop-do-while nil :while)) ; Normal, do while
1967                          (until (loop-do-while t :until)) ;Negate test on while
1968                          (when (loop-do-if when nil))   ; Normal, do when
1969                          (if (loop-do-if if nil))       ; synonymous
1970                          (unless (loop-do-if unless t)) ; Negate test on when
1971                          (with (loop-do-with))
1972                          (repeat (loop-do-repeat)))
1973              :for-keywords '((= (loop-ansi-for-equals))
1974                              (across (loop-for-across))
1975                              (in (loop-for-in))
1976                              (on (loop-for-on))
1977                              (from (loop-for-arithmetic :from))
1978                              (downfrom (loop-for-arithmetic :downfrom))
1979                              (upfrom (loop-for-arithmetic :upfrom))
1980                              (below (loop-for-arithmetic :below))
1981                              (above (loop-for-arithmetic :above))
1982                              (to (loop-for-arithmetic :to))
1983                              (upto (loop-for-arithmetic :upto))
1984                              (downto (loop-for-arithmetic :downto))
1985                              (by (loop-for-arithmetic :by))
1986                              (being (loop-for-being)))
1987              :iteration-keywords '((for (loop-do-for))
1988                                    (as (loop-do-for)))
1989              :type-symbols '(array atom bignum bit bit-vector character
1990                              compiled-function complex cons double-float
1991                              fixnum float function hash-table integer
1992                              keyword list long-float nil null number
1993                              package pathname random-state ratio rational
1994                              readtable sequence short-float simple-array
1995                              simple-bit-vector simple-string simple-vector
1996                              single-float standard-char stream string
1997                              base-char symbol t vector)
1998              :type-keywords nil
1999              :ansi (if extended-p :extended t))))
2000     (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
2001                    :preposition-groups '((:of :in))
2002                    :inclusive-permitted nil
2003                    :user-data '(:which :hash-key))
2004     (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
2005                    :preposition-groups '((:of :in))
2006                    :inclusive-permitted nil
2007                    :user-data '(:which :hash-value))
2008     (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
2009                    :preposition-groups '((:of :in))
2010                    :inclusive-permitted nil
2011                    :user-data '(:symbol-types (:internal
2012                                                :external
2013                                                :inherited)))
2014     (add-loop-path '(external-symbol external-symbols)
2015                    'loop-package-symbols-iteration-path w
2016                    :preposition-groups '((:of :in))
2017                    :inclusive-permitted nil
2018                    :user-data '(:symbol-types (:external)))
2019     (add-loop-path '(present-symbol present-symbols)
2020                    'loop-package-symbols-iteration-path w
2021                    :preposition-groups '((:of :in))
2022                    :inclusive-permitted nil
2023                    :user-data '(:symbol-types (:internal
2024                                                :external)))
2025     w))
2026
2027 (defparameter *loop-ansi-universe*
2028   (make-ansi-loop-universe nil))
2029
2030 (defun loop-standard-expansion (keywords-and-forms environment universe)
2031   (if (and keywords-and-forms (symbolp (car keywords-and-forms)))
2032       (loop-translate keywords-and-forms environment universe)
2033       (let ((tag (gensym)))
2034         `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
2035
2036 (sb!int:defmacro-mundanely loop (&environment env &rest keywords-and-forms)
2037   (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))
2038
2039 (sb!int:defmacro-mundanely loop-finish ()
2040   #!+sb-doc
2041   "Cause the iteration to terminate \"normally\", the same as implicit
2042 termination by an iteration driving clause, or by use of WHILE or
2043 UNTIL -- the epilogue code (if any) will be run, and any implicitly
2044 collected result will be returned as the value of the LOOP."
2045   '(go end-loop))