3e413fcc7f8aff659afcbc493a43372e61f21480
[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
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
351              ;; recurse 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-VARIABLE.
427 (defvar *loop-named-variables*)
428
429 ;;; LETlist-like list being accumulated for one group of parallel bindings.
430 (defvar *loop-variables*)
431
432 ;;; list of declarations being accumulated in parallel with *LOOP-VARIABLES*
433 (defvar *loop-declarations*)
434
435 ;;; This is used by LOOP for destructuring binding, if it is doing
436 ;;; that itself. See LOOP-MAKE-VARIABLE.
437 (defvar *loop-desetq-crocks*)
438
439 ;;; list of wrapping forms, innermost first, which go immediately
440 ;;; inside the current set of parallel bindings being accumulated in
441 ;;; *LOOP-VARIABLES*. The wrappers are appended onto a body. E.g.,
442 ;;; this list could conceivably have as its value
443 ;;;   ((WITH-OPEN-FILE (G0001 G0002 ...))),
444 ;;; with G0002 being one of the bindings in *LOOP-VARIABLES* (This is
445 ;;; why the wrappers go inside of the variable bindings).
446 (defvar *loop-wrappers*)
447
448 ;;; This accumulates lists of previous values of *LOOP-VARIABLES* and
449 ;;; the other lists above, for each new nesting of bindings. See
450 ;;; LOOP-BIND-BLOCK.
451 (defvar *loop-bind-stack*)
452
453 ;;; This is simply a list of LOOP iteration variables, used for
454 ;;; checking for duplications.
455 (defvar *loop-iteration-variables*)
456
457 ;;; list of prologue forms of the loop, accumulated in reverse order
458 (defvar *loop-prologue*)
459
460 (defvar *loop-before-loop*)
461 (defvar *loop-body*)
462 (defvar *loop-after-body*)
463
464 ;;; This is T if we have emitted any body code, so that iteration
465 ;;; driving clauses can be disallowed. This is not strictly the same
466 ;;; as checking *LOOP-BODY*, because we permit some clauses such as
467 ;;; RETURN to not be considered "real" body (so as to permit the user
468 ;;; to "code" an abnormal return value "in loop").
469 (defvar *loop-emitted-body*)
470
471 ;;; list of epilogue forms (supplied by FINALLY generally), accumulated
472 ;;; in reverse order
473 (defvar *loop-epilogue*)
474
475 ;;; list of epilogue forms which are supplied after the above "user"
476 ;;; epilogue. "Normal" termination return values are provide by
477 ;;; putting the return form in here. Normally this is done using
478 ;;; LOOP-EMIT-FINAL-VALUE, q.v.
479 (defvar *loop-after-epilogue*)
480
481 ;;; the "culprit" responsible for supplying a final value from the
482 ;;; loop. This is so LOOP-EMIT-FINAL-VALUE can moan about multiple
483 ;;; return values being supplied.
484 (defvar *loop-final-value-culprit*)
485
486 ;;; If this is true, we are in some branch of a conditional. Some
487 ;;; clauses may be disallowed.
488 (defvar *loop-inside-conditional*)
489
490 ;;; If not NIL, this is a temporary bound around the loop for holding
491 ;;; the temporary value for "it" in things like "when (f) collect it".
492 ;;; It may be used as a supertemporary by some other things.
493 (defvar *loop-when-it-variable*)
494
495 ;;; Sometimes we decide we need to fold together parts of the loop,
496 ;;; but some part of the generated iteration code is different for the
497 ;;; first and remaining iterations. This variable will be the
498 ;;; temporary which is the flag used in the loop to tell whether we
499 ;;; are in the first or remaining iterations.
500 (defvar *loop-never-stepped-variable*)
501
502 ;;; list of all the value-accumulation descriptor structures in the
503 ;;; loop. See LOOP-GET-COLLECTION-INFO.
504 (defvar *loop-collection-cruft*) ; for multiple COLLECTs (etc.)
505 \f
506 ;;;; code analysis stuff
507
508 (defun loop-constant-fold-if-possible (form &optional expected-type)
509   (let ((new-form form) (constantp nil) (constant-value nil))
510     (when (setq constantp (constantp new-form))
511       (setq constant-value (eval new-form)))
512     (when (and constantp expected-type)
513       (unless (sb!xc:typep constant-value expected-type)
514         (loop-warn "The form ~S evaluated to ~S, which was not of the anticipated type ~S."
515                    form constant-value expected-type)
516         (setq constantp nil constant-value nil)))
517     (values new-form constantp constant-value)))
518
519 (defun loop-constantp (form)
520   (constantp form))
521 \f
522 ;;;; LOOP iteration optimization
523
524 (defvar *loop-duplicate-code*
525         nil)
526
527 (defvar *loop-iteration-flag-variable*
528         (make-symbol "LOOP-NOT-FIRST-TIME"))
529
530 (defun loop-code-duplication-threshold (env)
531   (declare (ignore env))
532   (let (;; If we could read optimization declaration information (as
533         ;; with the DECLARATION-INFORMATION function (present in
534         ;; CLTL2, removed from ANSI standard) we could set these
535         ;; values flexibly. Without DECLARATION-INFORMATION, we have
536         ;; to set them to constants.
537         (speed 1)
538         (space 1))
539     (+ 40 (* (- speed space) 10))))
540
541 (sb!int:defmacro-mundanely loop-body (&environment env
542                                          prologue
543                                          before-loop
544                                          main-body
545                                          after-loop
546                                          epilogue
547                                          &aux rbefore rafter flagvar)
548   (unless (= (length before-loop) (length after-loop))
549     (error "LOOP-BODY called with non-synched before- and after-loop lists"))
550   ;;All our work is done from these copies, working backwards from the end:
551   (setq rbefore (reverse before-loop) rafter (reverse after-loop))
552   (labels ((psimp (l)
553              (let ((ans nil))
554                (dolist (x l)
555                  (when x
556                    (push x ans)
557                    (when (and (consp x)
558                               (member (car x) '(go return return-from)))
559                      (return nil))))
560                (nreverse ans)))
561            (pify (l) (if (null (cdr l)) (car l) `(progn ,@l)))
562            (makebody ()
563              (let ((form `(tagbody
564                             ,@(psimp (append prologue (nreverse rbefore)))
565                          next-loop
566                             ,@(psimp (append main-body
567                                              (nreconc rafter
568                                                       `((go next-loop)))))
569                          end-loop
570                             ,@(psimp epilogue))))
571                (if flagvar `(let ((,flagvar nil)) ,form) form))))
572     (when (or *loop-duplicate-code* (not rbefore))
573       (return-from loop-body (makebody)))
574     ;; This outer loop iterates once for each not-first-time flag test
575     ;; generated plus once more for the forms that don't need a flag test.
576     (do ((threshold (loop-code-duplication-threshold env))) (nil)
577       (declare (fixnum threshold))
578       ;; Go backwards from the ends of before-loop and after-loop
579       ;; merging all the equivalent forms into the body.
580       (do () ((or (null rbefore) (not (equal (car rbefore) (car rafter)))))
581         (push (pop rbefore) main-body)
582         (pop rafter))
583       (unless rbefore (return (makebody)))
584       ;; The first forms in RBEFORE & RAFTER (which are the
585       ;; chronologically last forms in the list) differ, therefore
586       ;; they cannot be moved into the main body. If everything that
587       ;; chronologically precedes them either differs or is equal but
588       ;; is okay to duplicate, we can just put all of rbefore in the
589       ;; prologue and all of rafter after the body. Otherwise, there
590       ;; is something that is not okay to duplicate, so it and
591       ;; everything chronologically after it in rbefore and rafter
592       ;; must go into the body, with a flag test to distinguish the
593       ;; first time around the loop from later times. What
594       ;; chronologically precedes the non-duplicatable form will be
595       ;; handled the next time around the outer loop.
596       (do ((bb rbefore (cdr bb))
597            (aa rafter (cdr aa))
598            (lastdiff nil)
599            (count 0)
600            (inc nil))
601           ((null bb) (return-from loop-body (makebody)))        ; Did it.
602         (cond ((not (equal (car bb) (car aa))) (setq lastdiff bb count 0))
603               ((or (not (setq inc (estimate-code-size (car bb) env)))
604                    (> (incf count inc) threshold))
605                ;; Ok, we have found a non-duplicatable piece of code.
606                ;; Everything chronologically after it must be in the
607                ;; central body. Everything chronologically at and
608                ;; after LASTDIFF goes into the central body under a
609                ;; flag test.
610                (let ((then nil) (else nil))
611                  (do () (nil)
612                    (push (pop rbefore) else)
613                    (push (pop rafter) then)
614                    (when (eq rbefore (cdr lastdiff)) (return)))
615                  (unless flagvar
616                    (push `(setq ,(setq flagvar *loop-iteration-flag-variable*)
617                                 t)
618                          else))
619                  (push `(if ,flagvar ,(pify (psimp then)) ,(pify (psimp else)))
620                        main-body))
621                ;; Everything chronologically before lastdiff until the
622                ;; non-duplicatable form (CAR BB) is the same in
623                ;; RBEFORE and RAFTER, so just copy it into the body.
624                (do () (nil)
625                  (pop rafter)
626                  (push (pop rbefore) main-body)
627                  (when (eq rbefore (cdr bb)) (return)))
628                (return)))))))
629 \f
630 (defun duplicatable-code-p (expr env)
631   (if (null expr) 0
632       (let ((ans (estimate-code-size expr env)))
633         (declare (fixnum ans))
634         ;; @@@@ Use (DECLARATION-INFORMATION 'OPTIMIZE ENV) here to
635         ;; get an alist of optimize quantities back to help quantify
636         ;; how much code we are willing to duplicate.
637         ans)))
638
639 (defvar *special-code-sizes*
640         '((return 0) (progn 0)
641           (null 1) (not 1) (eq 1) (car 1) (cdr 1)
642           (when 1) (unless 1) (if 1)
643           (caar 2) (cadr 2) (cdar 2) (cddr 2)
644           (caaar 3) (caadr 3) (cadar 3) (caddr 3)
645           (cdaar 3) (cdadr 3) (cddar 3) (cdddr 3)
646           (caaaar 4) (caaadr 4) (caadar 4) (caaddr 4)
647           (cadaar 4) (cadadr 4) (caddar 4) (cadddr 4)
648           (cdaaar 4) (cdaadr 4) (cdadar 4) (cdaddr 4)
649           (cddaar 4) (cddadr 4) (cdddar 4) (cddddr 4)))
650
651 (defvar *estimate-code-size-punt*
652         '(block
653            do do* dolist
654            flet
655            labels lambda let let* locally
656            macrolet multiple-value-bind
657            prog prog*
658            symbol-macrolet
659            tagbody
660            unwind-protect
661            with-open-file))
662
663 (defun destructuring-size (x)
664   (do ((x x (cdr x)) (n 0 (+ (destructuring-size (car x)) n)))
665       ((atom x) (+ n (if (null x) 0 1)))))
666
667 (defun estimate-code-size (x env)
668   (catch 'estimate-code-size
669     (estimate-code-size-1 x env)))
670
671 (defun estimate-code-size-1 (x env)
672   (flet ((list-size (l)
673            (let ((n 0))
674              (declare (fixnum n))
675              (dolist (x l n) (incf n (estimate-code-size-1 x env))))))
676     ;;@@@@ ???? (declare (function list-size (list) fixnum))
677     (cond ((constantp x) 1)
678           ((symbolp x) (multiple-value-bind (new-form expanded-p)
679                            (sb!xc:macroexpand-1 x env)
680                          (if expanded-p
681                              (estimate-code-size-1 new-form env)
682                              1)))
683           ((atom x) 1) ;; ??? self-evaluating???
684           ((symbolp (car x))
685            (let ((fn (car x)) (tem nil) (n 0))
686              (declare (symbol fn) (fixnum n))
687              (macrolet ((f (overhead &optional (args nil args-p))
688                           `(the fixnum (+ (the fixnum ,overhead)
689                                           (the fixnum
690                                                (list-size ,(if args-p
691                                                                args
692                                                              '(cdr x))))))))
693                (cond ((setq tem (get fn 'estimate-code-size))
694                       (typecase tem
695                         (fixnum (f tem))
696                         (t (funcall tem x env))))
697                      ((setq tem (assoc fn *special-code-sizes*))
698                       (f (second tem)))
699                      ((eq fn 'cond)
700                       (dolist (clause (cdr x) n)
701                         (incf n (list-size clause)) (incf n)))
702                      ((eq fn 'desetq)
703                       (do ((l (cdr x) (cdr l))) ((null l) n)
704                         (setq n (+ n
705                                    (destructuring-size (car l))
706                                    (estimate-code-size-1 (cadr l) env)))))
707                      ((member fn '(setq psetq))
708                       (do ((l (cdr x) (cdr l))) ((null l) n)
709                         (setq n (+ n (estimate-code-size-1 (cadr l) env) 1))))
710                      ((eq fn 'go) 1)
711                      ((eq fn 'function)
712                       ;; This skirts the issue of implementationally-defined
713                       ;; lambda macros by recognizing CL function names and
714                       ;; nothing else.
715                       (if (or (symbolp (cadr x))
716                               (and (consp (cadr x)) (eq (caadr x) 'setf)))
717                           1
718                           (throw 'duplicatable-code-p nil)))
719                      ((eq fn 'multiple-value-setq)
720                       (f (length (second x)) (cddr x)))
721                      ((eq fn 'return-from)
722                       (1+ (estimate-code-size-1 (third x) env)))
723                      ((or (special-operator-p fn)
724                           (member fn *estimate-code-size-punt*))
725                       (throw 'estimate-code-size nil))
726                      (t (multiple-value-bind (new-form expanded-p)
727                             (sb!xc:macroexpand-1 x env)
728                           (if expanded-p
729                               (estimate-code-size-1 new-form env)
730                               (f 3))))))))
731           (t (throw 'estimate-code-size nil)))))
732 \f
733 ;;;; loop errors
734
735 (defun loop-context ()
736   (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
737       ((eq l (cdr *loop-source-code*)) (nreverse new))))
738
739 (defun loop-error (format-string &rest format-args)
740   (error "~?~%current LOOP context:~{ ~S~}."
741          format-string
742          format-args
743          (loop-context)))
744
745 (defun loop-warn (format-string &rest format-args)
746   (warn "~?~%current LOOP context:~{ ~S~}."
747         format-string
748         format-args
749         (loop-context)))
750
751 (defun loop-check-data-type (specified-type required-type
752                              &optional (default-type required-type))
753   (if (null specified-type)
754       default-type
755       (multiple-value-bind (a b) (sb!xc:subtypep specified-type required-type)
756         (cond ((not b)
757                (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
758                           specified-type required-type))
759               ((not a)
760                (loop-error "The specified data type ~S is not a subtype of ~S."
761                            specified-type required-type)))
762         specified-type)))
763 \f
764 (defun loop-build-destructuring-bindings (crocks forms)
765   (if crocks
766       `((destructuring-bind ,(car crocks) ,(cadr crocks)
767         ,@(loop-build-destructuring-bindings (cddr crocks) forms)))
768       forms))
769
770 (defun loop-translate (*loop-source-code*
771                        *loop-macro-environment*
772                        *loop-universe*)
773   (let ((*loop-original-source-code* *loop-source-code*)
774         (*loop-source-context* nil)
775         (*loop-iteration-variables* nil)
776         (*loop-variables* nil)
777         (*loop-named-variables* nil)
778         (*loop-declarations* nil)
779         (*loop-desetq-crocks* nil)
780         (*loop-bind-stack* nil)
781         (*loop-prologue* nil)
782         (*loop-wrappers* nil)
783         (*loop-before-loop* nil)
784         (*loop-body* nil)
785         (*loop-emitted-body* nil)
786         (*loop-after-body* nil)
787         (*loop-epilogue* nil)
788         (*loop-after-epilogue* nil)
789         (*loop-final-value-culprit* nil)
790         (*loop-inside-conditional* nil)
791         (*loop-when-it-variable* nil)
792         (*loop-never-stepped-variable* nil)
793         (*loop-names* nil)
794         (*loop-collection-cruft* nil))
795     (loop-iteration-driver)
796     (loop-bind-block)
797     (let ((answer `(loop-body
798                      ,(nreverse *loop-prologue*)
799                      ,(nreverse *loop-before-loop*)
800                      ,(nreverse *loop-body*)
801                      ,(nreverse *loop-after-body*)
802                      ,(nreconc *loop-epilogue*
803                                (nreverse *loop-after-epilogue*)))))
804       (do () (nil)
805         (setq answer `(block ,(pop *loop-names*) ,answer))
806         (unless *loop-names* (return nil)))
807       (dolist (entry *loop-bind-stack*)
808         (let ((vars (first entry))
809               (dcls (second entry))
810               (crocks (third entry))
811               (wrappers (fourth entry)))
812           (dolist (w wrappers)
813             (setq answer (append w (list answer))))
814           (when (or vars dcls crocks)
815             (let ((forms (list answer)))
816               ;;(when crocks (push crocks forms))
817               (when dcls (push `(declare ,@dcls) forms))
818               (setq answer `(,(if vars 'let 'locally)
819                              ,vars
820                              ,@(loop-build-destructuring-bindings crocks
821                                                                   forms)))))))
822       answer)))
823
824 (defun loop-iteration-driver ()
825   (do () ((null *loop-source-code*))
826     (let ((keyword (car *loop-source-code*)) (tem nil))
827       (cond ((not (symbolp keyword))
828              (loop-error "~S found where LOOP keyword expected" keyword))
829             (t (setq *loop-source-context* *loop-source-code*)
830                (loop-pop-source)
831                (cond ((setq tem
832                             (loop-lookup-keyword keyword
833                                                  (loop-universe-keywords
834                                                   *loop-universe*)))
835                       ;; It's a "miscellaneous" toplevel LOOP keyword (DO,
836                       ;; COLLECT, NAMED, etc.)
837                       (apply (symbol-function (first tem)) (rest tem)))
838                      ((setq tem
839                             (loop-lookup-keyword keyword
840                                                  (loop-universe-iteration-keywords *loop-universe*)))
841                       (loop-hack-iteration tem))
842                      ((loop-tmember keyword '(and else))
843                       ;; The alternative is to ignore it, i.e. let it go
844                       ;; around to the next keyword...
845                       (loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
846                                   keyword
847                                   (car *loop-source-code*)
848                                   (cadr *loop-source-code*)))
849                      (t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
850 \f
851 (defun loop-pop-source ()
852   (if *loop-source-code*
853       (pop *loop-source-code*)
854       (loop-error "LOOP source code ran out when another token was expected.")))
855
856 (defun loop-get-form ()
857   (if *loop-source-code*
858       (loop-pop-source)
859       (loop-error "LOOP code ran out where a form was expected.")))
860
861 (defun loop-get-compound-form ()
862   (let ((form (loop-get-form)))
863     (unless (consp form)
864       (loop-error "A compound form was expected, but ~S found." form))
865     form))
866
867 (defun loop-get-progn ()
868   (do ((forms (list (loop-get-compound-form))
869               (cons (loop-get-compound-form) forms))
870        (nextform (car *loop-source-code*)
871                  (car *loop-source-code*)))
872       ((atom nextform)
873        (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
874
875 (defun loop-construct-return (form)
876   `(return-from ,(car *loop-names*) ,form))
877
878 (defun loop-pseudo-body (form)
879   (cond ((or *loop-emitted-body* *loop-inside-conditional*)
880          (push form *loop-body*))
881         (t (push form *loop-before-loop*) (push form *loop-after-body*))))
882
883 (defun loop-emit-body (form)
884   (setq *loop-emitted-body* t)
885   (loop-pseudo-body form))
886
887 (defun loop-emit-final-value (form)
888   (push (loop-construct-return form) *loop-after-epilogue*)
889   (when *loop-final-value-culprit*
890     (loop-warn "The LOOP clause is providing a value for the iteration,~@
891                 however one was already established by a ~S clause."
892                *loop-final-value-culprit*))
893   (setq *loop-final-value-culprit* (car *loop-source-context*)))
894
895 (defun loop-disallow-conditional (&optional kwd)
896   (when *loop-inside-conditional*
897     (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
898 \f
899 ;;;; loop types
900
901 (defun loop-typed-init (data-type)
902   (when (and data-type (sb!xc:subtypep data-type 'number))
903     (if (or (sb!xc:subtypep data-type 'float)
904             (sb!xc:subtypep data-type '(complex float)))
905         (coerce 0 data-type)
906         0)))
907
908 (defun loop-optional-type (&optional variable)
909   ;; No variable specified implies that no destructuring is permissible.
910   (and *loop-source-code* ; Don't get confused by NILs..
911        (let ((z (car *loop-source-code*)))
912          (cond ((loop-tequal z 'of-type)
913                 ;; This is the syntactically unambigous form in that
914                 ;; the form of the type specifier does not matter.
915                 ;; Also, it is assumed that the type specifier is
916                 ;; unambiguously, and without need of translation, a
917                 ;; common lisp type specifier or pattern (matching the
918                 ;; variable) thereof.
919                 (loop-pop-source)
920                 (loop-pop-source))
921
922                ((symbolp z)
923                 ;; This is the (sort of) "old" syntax, even though we
924                 ;; didn't used to support all of these type symbols.
925                 (let ((type-spec (or (gethash z
926                                               (loop-universe-type-symbols
927                                                *loop-universe*))
928                                      (gethash (symbol-name z)
929                                               (loop-universe-type-keywords
930                                                *loop-universe*)))))
931                   (when type-spec
932                     (loop-pop-source)
933                     type-spec)))
934                (t
935                 ;; This is our sort-of old syntax. But this is only
936                 ;; valid for when we are destructuring, so we will be
937                 ;; compulsive (should we really be?) and require that
938                 ;; we in fact be doing variable destructuring here. We
939                 ;; must translate the old keyword pattern typespec
940                 ;; into a fully-specified pattern of real type
941                 ;; specifiers here.
942                 (if (consp variable)
943                     (unless (consp z)
944                      (loop-error
945                         "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
946                         z))
947                     (loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
948                 (loop-pop-source)
949                 (labels ((translate (k v)
950                            (cond ((null k) nil)
951                                  ((atom k)
952                                   (replicate
953                                     (or (gethash k
954                                                  (loop-universe-type-symbols
955                                                   *loop-universe*))
956                                         (gethash (symbol-name k)
957                                                  (loop-universe-type-keywords
958                                                   *loop-universe*))
959                                         (loop-error
960                                           "The destructuring type pattern ~S contains the unrecognized type keyword ~S."
961                                           z k))
962                                     v))
963                                  ((atom v)
964                                   (loop-error
965                                     "The destructuring type pattern ~S doesn't match the variable pattern ~S."
966                                     z variable))
967                                  (t (cons (translate (car k) (car v))
968                                           (translate (cdr k) (cdr v))))))
969                          (replicate (typ v)
970                            (if (atom v)
971                                typ
972                                (cons (replicate typ (car v))
973                                      (replicate typ (cdr v))))))
974                   (translate z variable)))))))
975 \f
976 ;;;; loop variables
977
978 (defun loop-bind-block ()
979   (when (or *loop-variables* *loop-declarations* *loop-wrappers*)
980     (push (list (nreverse *loop-variables*)
981                 *loop-declarations*
982                 *loop-desetq-crocks*
983                 *loop-wrappers*)
984           *loop-bind-stack*)
985     (setq *loop-variables* nil
986           *loop-declarations* nil
987           *loop-desetq-crocks* nil
988           *loop-wrappers* nil)))
989
990 (defun loop-make-variable (name initialization dtype
991                            &optional iteration-variable-p)
992   (cond ((null name)
993          (cond ((not (null initialization))
994                 (push (list (setq name (gensym "LOOP-IGNORE-"))
995                             initialization)
996                       *loop-variables*)
997                 (push `(ignore ,name) *loop-declarations*))))
998         ((atom name)
999          (cond (iteration-variable-p
1000                 (if (member name *loop-iteration-variables*)
1001                     (loop-error "duplicated LOOP iteration variable ~S" name)
1002                     (push name *loop-iteration-variables*)))
1003                ((assoc name *loop-variables*)
1004                 (loop-error "duplicated variable ~S in LOOP parallel binding"
1005                             name)))
1006          (unless (symbolp name)
1007            (loop-error "bad variable ~S somewhere in LOOP" name))
1008          (loop-declare-variable name dtype)
1009          ;; We use ASSOC on this list to check for duplications (above),
1010          ;; so don't optimize out this list:
1011          (push (list name (or initialization (loop-typed-init dtype)))
1012                *loop-variables*))
1013         (initialization
1014          (let ((newvar (gensym "LOOP-DESTRUCTURE-")))
1015            (loop-declare-variable name dtype)
1016            (push (list newvar initialization) *loop-variables*)
1017            ;; *LOOP-DESETQ-CROCKS* gathered in reverse order.
1018            (setq *loop-desetq-crocks*
1019                  (list* name newvar *loop-desetq-crocks*))))
1020         (t (let ((tcar nil) (tcdr nil))
1021              (if (atom dtype) (setq tcar (setq tcdr dtype))
1022                  (setq tcar (car dtype) tcdr (cdr dtype)))
1023              (loop-make-variable (car name) nil tcar iteration-variable-p)
1024              (loop-make-variable (cdr name) nil tcdr iteration-variable-p))))
1025   name)
1026
1027 (defun loop-make-iteration-variable (name initialization dtype)
1028   (loop-make-variable name initialization dtype t))
1029
1030 (defun loop-declare-variable (name dtype)
1031   (cond ((or (null name) (null dtype) (eq dtype t)) nil)
1032         ((symbolp name)
1033          (unless (sb!xc:subtypep t dtype)
1034            (let ((dtype (let ((init (loop-typed-init dtype)))
1035                           (if (sb!xc:typep init dtype)
1036                               dtype
1037                               `(or (member ,init) ,dtype)))))
1038              (push `(type ,dtype ,name) *loop-declarations*))))
1039         ((consp name)
1040          (cond ((consp dtype)
1041                 (loop-declare-variable (car name) (car dtype))
1042                 (loop-declare-variable (cdr name) (cdr dtype)))
1043                (t (loop-declare-variable (car name) dtype)
1044                   (loop-declare-variable (cdr name) dtype))))
1045         (t (error "invalid LOOP variable passed in: ~S" name))))
1046
1047 (defun loop-maybe-bind-form (form data-type)
1048   (if (loop-constantp form)
1049       form
1050       (loop-make-variable (gensym "LOOP-BIND-") form data-type)))
1051 \f
1052 (defun loop-do-if (for negatep)
1053   (let ((form (loop-get-form)) (*loop-inside-conditional* t) (it-p nil))
1054     (flet ((get-clause (for)
1055              (do ((body nil)) (nil)
1056                (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
1057                  (cond ((not (symbolp key))
1058                         (loop-error
1059                           "~S found where keyword expected getting LOOP clause after ~S"
1060                           key for))
1061                        (t (setq *loop-source-context* *loop-source-code*)
1062                           (loop-pop-source)
1063                           (when (loop-tequal (car *loop-source-code*) 'it)
1064                             (setq *loop-source-code*
1065                                   (cons (or it-p
1066                                             (setq it-p
1067                                                   (loop-when-it-variable)))
1068                                         (cdr *loop-source-code*))))
1069                           (cond ((or (not (setq data (loop-lookup-keyword
1070                                                        key (loop-universe-keywords *loop-universe*))))
1071                                      (progn (apply (symbol-function (car data))
1072                                                    (cdr data))
1073                                             (null *loop-body*)))
1074                                  (loop-error
1075                                    "~S does not introduce a LOOP clause that can follow ~S."
1076                                    key for))
1077                                 (t (setq body (nreconc *loop-body* body)))))))
1078                (if (loop-tequal (car *loop-source-code*) :and)
1079                    (loop-pop-source)
1080                    (return (if (cdr body)
1081                                `(progn ,@(nreverse body))
1082                                (car body)))))))
1083       (let ((then (get-clause for))
1084             (else (when (loop-tequal (car *loop-source-code*) :else)
1085                     (loop-pop-source)
1086                     (list (get-clause :else)))))
1087         (when (loop-tequal (car *loop-source-code*) :end)
1088           (loop-pop-source))
1089         (when it-p (setq form `(setq ,it-p ,form)))
1090         (loop-pseudo-body
1091           `(if ,(if negatep `(not ,form) form)
1092                ,then
1093                ,@else))))))
1094
1095 (defun loop-do-initially ()
1096   (loop-disallow-conditional :initially)
1097   (push (loop-get-progn) *loop-prologue*))
1098
1099 (defun loop-do-finally ()
1100   (loop-disallow-conditional :finally)
1101   (push (loop-get-progn) *loop-epilogue*))
1102
1103 (defun loop-do-do ()
1104   (loop-emit-body (loop-get-progn)))
1105
1106 (defun loop-do-named ()
1107   (let ((name (loop-pop-source)))
1108     (unless (symbolp name)
1109       (loop-error "~S is an invalid name for your LOOP" name))
1110     (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1111       (loop-error "The NAMED ~S clause occurs too late." name))
1112     (when *loop-names*
1113       (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1114                   (car *loop-names*) name))
1115     (setq *loop-names* (list name nil))))
1116
1117 (defun loop-do-return ()
1118   (loop-pseudo-body (loop-construct-return (loop-get-form))))
1119 \f
1120 ;;;; value accumulation: LIST
1121
1122 (defstruct (loop-collector
1123             (:copier nil)
1124             (:predicate nil))
1125   name
1126   class
1127   (history nil)
1128   (tempvars nil)
1129   dtype
1130   (data nil)) ;collector-specific data
1131
1132 (defun loop-get-collection-info (collector class default-type)
1133   (let ((form (loop-get-form))
1134         (dtype (and (not (loop-universe-ansi *loop-universe*)) (loop-optional-type)))
1135         (name (when (loop-tequal (car *loop-source-code*) 'into)
1136                 (loop-pop-source)
1137                 (loop-pop-source))))
1138     (when (not (symbolp name))
1139       (loop-error "The value accumulation recipient name, ~S, is not a symbol." name))
1140     (unless dtype
1141       (setq dtype (or (loop-optional-type) default-type)))
1142     (let ((cruft (find (the symbol name) *loop-collection-cruft*
1143                        :key #'loop-collector-name)))
1144       (cond ((not cruft)
1145              (push (setq cruft (make-loop-collector
1146                                  :name name :class class
1147                                  :history (list collector) :dtype dtype))
1148                    *loop-collection-cruft*))
1149             (t (unless (eq (loop-collector-class cruft) class)
1150                  (loop-error
1151                    "incompatible kinds of LOOP value accumulation specified for collecting~@
1152                     ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S"
1153                    name (car (loop-collector-history cruft)) collector))
1154                (unless (equal dtype (loop-collector-dtype cruft))
1155                  (loop-warn
1156                    "unequal datatypes specified in different LOOP value accumulations~@
1157                    into ~S: ~S and ~S"
1158                    name dtype (loop-collector-dtype cruft))
1159                  (when (eq (loop-collector-dtype cruft) t)
1160                    (setf (loop-collector-dtype cruft) dtype)))
1161                (push collector (loop-collector-history cruft))))
1162       (values cruft form))))
1163
1164 (defun loop-list-collection (specifically)      ; NCONC, LIST, or APPEND
1165   (multiple-value-bind (lc form)
1166       (loop-get-collection-info specifically 'list 'list)
1167     (let ((tempvars (loop-collector-tempvars lc)))
1168       (unless tempvars
1169         (setf (loop-collector-tempvars lc)
1170               (setq tempvars (list* (gensym "LOOP-LIST-HEAD-")
1171                                     (gensym "LOOP-LIST-TAIL-")
1172                                     (and (loop-collector-name lc)
1173                                          (list (loop-collector-name lc))))))
1174         (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1175         (unless (loop-collector-name lc)
1176           (loop-emit-final-value `(loop-collect-answer ,(car tempvars)
1177                                                        ,@(cddr tempvars)))))
1178       (ecase specifically
1179         (list (setq form `(list ,form)))
1180         (nconc nil)
1181         (append (unless (and (consp form) (eq (car form) 'list))
1182                   (setq form `(copy-list ,form)))))
1183       (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1184 \f
1185 ;;;; value accumulation: MAX, MIN, SUM, COUNT
1186
1187 (defun loop-sum-collection (specifically required-type default-type);SUM, COUNT
1188   (multiple-value-bind (lc form)
1189       (loop-get-collection-info specifically 'sum default-type)
1190     (loop-check-data-type (loop-collector-dtype lc) required-type)
1191     (let ((tempvars (loop-collector-tempvars lc)))
1192       (unless tempvars
1193         (setf (loop-collector-tempvars lc)
1194               (setq tempvars (list (loop-make-variable
1195                                      (or (loop-collector-name lc)
1196                                          (gensym "LOOP-SUM-"))
1197                                      nil (loop-collector-dtype lc)))))
1198         (unless (loop-collector-name lc)
1199           (loop-emit-final-value (car (loop-collector-tempvars lc)))))
1200       (loop-emit-body
1201         (if (eq specifically 'count)
1202             `(when ,form
1203                (setq ,(car tempvars)
1204                      (1+ ,(car tempvars))))
1205             `(setq ,(car tempvars)
1206                    (+ ,(car tempvars)
1207                       ,form)))))))
1208
1209 (defun loop-maxmin-collection (specifically)
1210   (multiple-value-bind (lc form)
1211       (loop-get-collection-info specifically 'maxmin 'real)
1212     (loop-check-data-type (loop-collector-dtype lc) 'real)
1213     (let ((data (loop-collector-data lc)))
1214       (unless data
1215         (setf (loop-collector-data lc)
1216               (setq data (make-loop-minimax
1217                            (or (loop-collector-name lc)
1218                                (gensym "LOOP-MAXMIN-"))
1219                            (loop-collector-dtype lc))))
1220         (unless (loop-collector-name lc)
1221           (loop-emit-final-value (loop-minimax-answer-variable data))))
1222       (loop-note-minimax-operation specifically data)
1223       (push `(with-minimax-value ,data) *loop-wrappers*)
1224       (loop-emit-body `(loop-accumulate-minimax-value ,data
1225                                                       ,specifically
1226                                                       ,form)))))
1227 \f
1228 ;;;; value accumulation: aggregate booleans
1229
1230 ;;; handling the ALWAYS and NEVER loop keywords
1231 ;;;
1232 ;;; Under ANSI these are not permitted to appear under conditionalization.
1233 (defun loop-do-always (restrictive negate)
1234   (let ((form (loop-get-form)))
1235     (when restrictive (loop-disallow-conditional))
1236     (loop-emit-body `(,(if negate 'when 'unless) ,form
1237                       ,(loop-construct-return nil)))
1238     (loop-emit-final-value t)))
1239
1240 ;;; handling the THEREIS loop keyword
1241 ;;;
1242 ;;; Under ANSI this is not permitted to appear under conditionalization.
1243 (defun loop-do-thereis (restrictive)
1244   (when restrictive (loop-disallow-conditional))
1245   (loop-emit-body `(when (setq ,(loop-when-it-variable) ,(loop-get-form))
1246                      ,(loop-construct-return *loop-when-it-variable*))))
1247 \f
1248 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1249   (loop-disallow-conditional kwd)
1250   (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1251
1252 (defun loop-do-with ()
1253   (loop-disallow-conditional :with)
1254   (do ((var) (val) (dtype)) (nil)
1255     (setq var (loop-pop-source)
1256           dtype (loop-optional-type var)
1257           val (cond ((loop-tequal (car *loop-source-code*) :=)
1258                      (loop-pop-source)
1259                      (loop-get-form))
1260                     (t nil)))
1261     (loop-make-variable var val dtype)
1262     (if (loop-tequal (car *loop-source-code*) :and)
1263         (loop-pop-source)
1264         (return (loop-bind-block)))))
1265 \f
1266 ;;;; the iteration driver
1267
1268 (defun loop-hack-iteration (entry)
1269   (flet ((make-endtest (list-of-forms)
1270            (cond ((null list-of-forms) nil)
1271                  ((member t list-of-forms) '(go end-loop))
1272                  (t `(when ,(if (null (cdr (setq list-of-forms
1273                                                  (nreverse list-of-forms))))
1274                                 (car list-of-forms)
1275                                 (cons 'or list-of-forms))
1276                        (go end-loop))))))
1277     (do ((pre-step-tests nil)
1278          (steps nil)
1279          (post-step-tests nil)
1280          (pseudo-steps nil)
1281          (pre-loop-pre-step-tests nil)
1282          (pre-loop-steps nil)
1283          (pre-loop-post-step-tests nil)
1284          (pre-loop-pseudo-steps nil)
1285          (tem) (data))
1286         (nil)
1287       ;; Note that we collect endtests in reverse order, but steps in correct
1288       ;; order. MAKE-ENDTEST does the nreverse for us.
1289       (setq tem (setq data
1290                       (apply (symbol-function (first entry)) (rest entry))))
1291       (and (car tem) (push (car tem) pre-step-tests))
1292       (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1293       (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1294       (setq pseudo-steps
1295             (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1296       (setq tem (cdr tem))
1297       (when *loop-emitted-body*
1298         (loop-error "iteration in LOOP follows body code"))
1299       (unless tem (setq tem data))
1300       (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1301       ;; FIXME: This (SETF FOO (NCONC FOO BAR)) idiom appears often enough
1302       ;; that it might be worth making it into an NCONCF macro.
1303       (setq pre-loop-steps
1304             (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1305       (when (car (setq tem (cdr tem)))
1306         (push (car tem) pre-loop-post-step-tests))
1307       (setq pre-loop-pseudo-steps
1308             (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1309       (unless (loop-tequal (car *loop-source-code*) :and)
1310         (setq *loop-before-loop*
1311               (list* (loop-make-desetq pre-loop-pseudo-steps)
1312                      (make-endtest pre-loop-post-step-tests)
1313                      (loop-make-psetq pre-loop-steps)
1314                      (make-endtest pre-loop-pre-step-tests)
1315                      *loop-before-loop*))
1316         (setq *loop-after-body*
1317               (list* (loop-make-desetq pseudo-steps)
1318                      (make-endtest post-step-tests)
1319                      (loop-make-psetq steps)
1320                      (make-endtest pre-step-tests)
1321                      *loop-after-body*))
1322         (loop-bind-block)
1323         (return nil))
1324       (loop-pop-source)                         ; Flush the "AND".
1325       (when (and (not (loop-universe-implicit-for-required *loop-universe*))
1326                  (setq tem
1327                        (loop-lookup-keyword
1328                         (car *loop-source-code*)
1329                         (loop-universe-iteration-keywords *loop-universe*))))
1330         ;; The latest ANSI clarification is that the FOR/AS after the AND must
1331         ;; NOT be supplied.
1332         (loop-pop-source)
1333         (setq entry tem)))))
1334 \f
1335 ;;;; main iteration drivers
1336
1337 ;;; FOR variable keyword ..args..
1338 (defun loop-do-for ()
1339   (let* ((var (loop-pop-source))
1340          (data-type (loop-optional-type var))
1341          (keyword (loop-pop-source))
1342          (first-arg nil)
1343          (tem nil))
1344     (setq first-arg (loop-get-form))
1345     (unless (and (symbolp keyword)
1346                  (setq tem (loop-lookup-keyword
1347                              keyword
1348                              (loop-universe-for-keywords *loop-universe*))))
1349       (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP."
1350                   keyword))
1351     (apply (car tem) var first-arg data-type (cdr tem))))
1352
1353 (defun loop-do-repeat ()
1354   (let ((form (loop-get-form))
1355         (type (loop-check-data-type (loop-optional-type)
1356                                     'real)))
1357     (when (and (consp form)
1358                (eq (car form) 'the)
1359                (sb!xc:subtypep (second form) type))
1360       (setq type (second form)))
1361     (multiple-value-bind (number constantp value)
1362         (loop-constant-fold-if-possible form type)
1363       (cond ((and constantp (<= value 1)) `(t () () () ,(<= value 0) () () ()))
1364             (t (let ((var (loop-make-variable (gensym "LOOP-REPEAT-")
1365                                               number
1366                                               type)))
1367                  (if constantp
1368                      `((not (plusp (setq ,var (1- ,var))))
1369                        () () () () () () ())
1370                      `((minusp (setq ,var (1- ,var)))
1371                        () () ()))))))))
1372
1373 (defun loop-when-it-variable ()
1374   (or *loop-when-it-variable*
1375       (setq *loop-when-it-variable*
1376             (loop-make-variable (gensym "LOOP-IT-") nil nil))))
1377 \f
1378 ;;;; various FOR/AS subdispatches
1379
1380 ;;; ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when
1381 ;;; the THEN is omitted (other than being more stringent in its
1382 ;;; placement), and like the old "FOR x FIRST y THEN z" when the THEN
1383 ;;; is present. I.e., the first initialization occurs in the loop body
1384 ;;; (first-step), not in the variable binding phase.
1385 (defun loop-ansi-for-equals (var val data-type)
1386   (loop-make-iteration-variable var nil data-type)
1387   (cond ((loop-tequal (car *loop-source-code*) :then)
1388          ;; Then we are the same as "FOR x FIRST y THEN z".
1389          (loop-pop-source)
1390          `(() (,var ,(loop-get-form)) () ()
1391            () (,var ,val) () ()))
1392         (t ;; We are the same as "FOR x = y".
1393          `(() (,var ,val) () ()))))
1394
1395 (defun loop-for-across (var val data-type)
1396   (loop-make-iteration-variable var nil data-type)
1397   (let ((vector-var (gensym "LOOP-ACROSS-VECTOR-"))
1398         (index-var (gensym "LOOP-ACROSS-INDEX-")))
1399     (multiple-value-bind (vector-form constantp vector-value)
1400         (loop-constant-fold-if-possible val 'vector)
1401       (loop-make-variable
1402         vector-var vector-form
1403         (if (and (consp vector-form) (eq (car vector-form) 'the))
1404             (cadr vector-form)
1405             'vector))
1406       (loop-make-variable index-var 0 'fixnum)
1407       (let* ((length 0)
1408              (length-form (cond ((not constantp)
1409                                  (let ((v (gensym "LOOP-ACROSS-LIMIT-")))
1410                                    (push `(setq ,v (length ,vector-var))
1411                                          *loop-prologue*)
1412                                    (loop-make-variable v 0 'fixnum)))
1413                                 (t (setq length (length vector-value)))))
1414              (first-test `(>= ,index-var ,length-form))
1415              (other-test first-test)
1416              (step `(,var (aref ,vector-var ,index-var)))
1417              (pstep `(,index-var (1+ ,index-var))))
1418         (declare (fixnum length))
1419         (when constantp
1420           (setq first-test (= length 0))
1421           (when (<= length 1)
1422             (setq other-test t)))
1423         `(,other-test ,step () ,pstep
1424           ,@(and (not (eq first-test other-test))
1425                  `(,first-test ,step () ,pstep)))))))
1426 \f
1427 ;;;; list iteration
1428
1429 (defun loop-list-step (listvar)
1430   ;; We are not equipped to analyze whether 'FOO is the same as #'FOO
1431   ;; here in any sensible fashion, so let's give an obnoxious warning
1432   ;; whenever 'FOO is used as the stepping function.
1433   ;;
1434   ;; While a Discerning Compiler may deal intelligently with
1435   ;; (FUNCALL 'FOO ...), not recognizing FOO may defeat some LOOP
1436   ;; optimizations.
1437   (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1438                         (loop-pop-source)
1439                         (loop-get-form))
1440                        (t '(function cdr)))))
1441     (cond ((and (consp stepper) (eq (car stepper) 'quote))
1442            (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1443            `(funcall ,stepper ,listvar))
1444           ((and (consp stepper) (eq (car stepper) 'function))
1445            (list (cadr stepper) listvar))
1446           (t
1447            `(funcall ,(loop-make-variable (gensym "LOOP-FN-")
1448                                           stepper
1449                                           'function)
1450                      ,listvar)))))
1451
1452 (defun loop-for-on (var val data-type)
1453   (multiple-value-bind (list constantp list-value)
1454       (loop-constant-fold-if-possible val)
1455     (let ((listvar var))
1456       (cond ((and var (symbolp var))
1457              (loop-make-iteration-variable var list data-type))
1458             (t (loop-make-variable (setq listvar (gensym)) list 'list)
1459                (loop-make-iteration-variable var nil data-type)))
1460       (let ((list-step (loop-list-step listvar)))
1461         (let* ((first-endtest
1462                 ;; mysterious comment from original CMU CL sources:
1463                 ;;   the following should use `atom' instead of `endp',
1464                 ;;   per [bug2428]
1465                 `(atom ,listvar))
1466                (other-endtest first-endtest))
1467           (when (and constantp (listp list-value))
1468             (setq first-endtest (null list-value)))
1469           (cond ((eq var listvar)
1470                  ;; The contour of the loop is different because we
1471                  ;; use the user's variable...
1472                  `(() (,listvar ,list-step)
1473                    ,other-endtest () () () ,first-endtest ()))
1474                 (t (let ((step `(,var ,listvar))
1475                          (pseudo `(,listvar ,list-step)))
1476                      `(,other-endtest ,step () ,pseudo
1477                        ,@(and (not (eq first-endtest other-endtest))
1478                               `(,first-endtest ,step () ,pseudo)))))))))))
1479
1480 (defun loop-for-in (var val data-type)
1481   (multiple-value-bind (list constantp list-value)
1482       (loop-constant-fold-if-possible val)
1483     (let ((listvar (gensym "LOOP-LIST-")))
1484       (loop-make-iteration-variable var nil data-type)
1485       (loop-make-variable listvar list 'list)
1486       (let ((list-step (loop-list-step listvar)))
1487         (let* ((first-endtest `(endp ,listvar))
1488                (other-endtest first-endtest)
1489                (step `(,var (car ,listvar)))
1490                (pseudo-step `(,listvar ,list-step)))
1491           (when (and constantp (listp list-value))
1492             (setq first-endtest (null list-value)))
1493           `(,other-endtest ,step () ,pseudo-step
1494             ,@(and (not (eq first-endtest other-endtest))
1495                    `(,first-endtest ,step () ,pseudo-step))))))))
1496 \f
1497 ;;;; iteration paths
1498
1499 (defstruct (loop-path
1500             (:copier nil)
1501             (:predicate nil))
1502   names
1503   preposition-groups
1504   inclusive-permitted
1505   function
1506   user-data)
1507
1508 (defun add-loop-path (names function universe
1509                       &key preposition-groups inclusive-permitted user-data)
1510   (declare (type loop-universe universe))
1511   (unless (listp names)
1512     (setq names (list names)))
1513   (let ((ht (loop-universe-path-keywords universe))
1514         (lp (make-loop-path
1515               :names (mapcar #'symbol-name names)
1516               :function function
1517               :user-data user-data
1518               :preposition-groups (mapcar (lambda (x)
1519                                             (if (listp x) x (list x)))
1520                                           preposition-groups)
1521               :inclusive-permitted inclusive-permitted)))
1522     (dolist (name names)
1523       (setf (gethash (symbol-name name) ht) lp))
1524     lp))
1525 \f
1526 ;;; Note:  path functions are allowed to use loop-make-variable, hack
1527 ;;; the prologue, etc.
1528 (defun loop-for-being (var val data-type)
1529   ;; FOR var BEING each/the pathname prep-phrases using-stuff... each/the =
1530   ;; EACH or THE. Not clear if it is optional, so I guess we'll warn.
1531   (let ((path nil)
1532         (data nil)
1533         (inclusive nil)
1534         (stuff nil)
1535         (initial-prepositions nil))
1536     (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1537           ((loop-tequal (car *loop-source-code*) :and)
1538            (loop-pop-source)
1539            (setq inclusive t)
1540            (unless (loop-tmember (car *loop-source-code*)
1541                                  '(:its :each :his :her))
1542              (loop-error "~S was found where ITS or EACH expected in LOOP iteration path syntax."
1543                          (car *loop-source-code*)))
1544            (loop-pop-source)
1545            (setq path (loop-pop-source))
1546            (setq initial-prepositions `((:in ,val))))
1547           (t (loop-error "unrecognizable LOOP iteration path syntax: missing EACH or THE?")))
1548     (cond ((not (symbolp path))
1549            (loop-error
1550             "~S was found where a LOOP iteration path name was expected."
1551             path))
1552           ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1553            (loop-error "~S is not the name of a LOOP iteration path." path))
1554           ((and inclusive (not (loop-path-inclusive-permitted data)))
1555            (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1556     (let ((fun (loop-path-function data))
1557           (preps (nconc initial-prepositions
1558                         (loop-collect-prepositional-phrases
1559                          (loop-path-preposition-groups data)
1560                          t)))
1561           (user-data (loop-path-user-data data)))
1562       (when (symbolp fun) (setq fun (symbol-function fun)))
1563       (setq stuff (if inclusive
1564                       (apply fun var data-type preps :inclusive t user-data)
1565                       (apply fun var data-type preps user-data))))
1566     (when *loop-named-variables*
1567       (loop-error "Unused USING variables: ~S." *loop-named-variables*))
1568     ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back).
1569     ;; Protect the system from the user and the user from himself.
1570     (unless (member (length stuff) '(6 10))
1571       (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1572                   path))
1573     (do ((l (car stuff) (cdr l)) (x)) ((null l))
1574       (if (atom (setq x (car l)))
1575           (loop-make-iteration-variable x nil nil)
1576           (loop-make-iteration-variable (car x) (cadr x) (caddr x))))
1577     (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1578     (cddr stuff)))
1579 \f
1580 (defun named-variable (name)
1581   (let ((tem (loop-tassoc name *loop-named-variables*)))
1582     (declare (list tem))
1583     (cond ((null tem) (values (gensym) nil))
1584           (t (setq *loop-named-variables* (delete tem *loop-named-variables*))
1585              (values (cdr tem) t)))))
1586
1587 (defun loop-collect-prepositional-phrases (preposition-groups
1588                                            &optional
1589                                            USING-allowed
1590                                            initial-phrases)
1591   (flet ((in-group-p (x group) (car (loop-tmember x group))))
1592     (do ((token nil)
1593          (prepositional-phrases initial-phrases)
1594          (this-group nil nil)
1595          (this-prep nil nil)
1596          (disallowed-prepositions
1597            (mapcan (lambda (x)
1598                      (copy-list
1599                       (find (car x) preposition-groups :test #'in-group-p)))
1600                    initial-phrases))
1601          (used-prepositions (mapcar #'car initial-phrases)))
1602         ((null *loop-source-code*) (nreverse prepositional-phrases))
1603       (declare (symbol this-prep))
1604       (setq token (car *loop-source-code*))
1605       (dolist (group preposition-groups)
1606         (when (setq this-prep (in-group-p token group))
1607           (return (setq this-group group))))
1608       (cond (this-group
1609              (when (member this-prep disallowed-prepositions)
1610                (loop-error
1611                  (if (member this-prep used-prepositions)
1612                      "A ~S prepositional phrase occurs multiply for some LOOP clause."
1613                      "Preposition ~S was used when some other preposition has subsumed it.")
1614                  token))
1615              (setq used-prepositions (if (listp this-group)
1616                                          (append this-group used-prepositions)
1617                                          (cons this-group used-prepositions)))
1618              (loop-pop-source)
1619              (push (list this-prep (loop-get-form)) prepositional-phrases))
1620             ((and USING-allowed (loop-tequal token 'using))
1621              (loop-pop-source)
1622              (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1623                (when (or (atom z)
1624                          (atom (cdr z))
1625                          (not (null (cddr z)))
1626                          (not (symbolp (car z)))
1627                          (and (cadr z) (not (symbolp (cadr z)))))
1628                  (loop-error "~S bad variable pair in path USING phrase" z))
1629                (when (cadr z)
1630                  (if (setq tem (loop-tassoc (car z) *loop-named-variables*))
1631                      (loop-error
1632                        "The variable substitution for ~S occurs twice in a USING phrase,~@
1633                         with ~S and ~S."
1634                        (car z) (cadr z) (cadr tem))
1635                      (push (cons (car z) (cadr z)) *loop-named-variables*)))
1636                (when (or (null *loop-source-code*)
1637                          (symbolp (car *loop-source-code*)))
1638                  (return nil))))
1639             (t (return (nreverse prepositional-phrases)))))))
1640 \f
1641 ;;;; master sequencer function
1642
1643 (defun loop-sequencer (indexv indexv-type 
1644                        variable variable-type
1645                        sequence-variable sequence-type
1646                        step-hack default-top
1647                        prep-phrases)
1648    (let ((endform nil) ; Form (constant or variable) with limit value
1649          (sequencep nil) ; T if sequence arg has been provided
1650          (testfn nil) ; endtest function
1651          (test nil) ; endtest form
1652          (stepby (1+ (or (loop-typed-init indexv-type) 0))) ; our increment
1653          (stepby-constantp t)
1654          (step nil) ; step form
1655          (dir nil) ; direction of stepping: NIL, :UP, :DOWN
1656          (inclusive-iteration nil) ; T if include last index
1657          (start-given nil) ; T when prep phrase has specified start
1658          (start-value nil)
1659          (start-constantp nil)
1660          (limit-given nil) ; T when prep phrase has specified end
1661          (limit-constantp nil)
1662          (limit-value nil)
1663          )
1664      (when variable (loop-make-iteration-variable variable nil variable-type))
1665      (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1666        (setq prep (caar l) form (cadar l))
1667        (case prep
1668          ((:of :in)
1669           (setq sequencep t)
1670           (loop-make-variable sequence-variable form sequence-type))
1671          ((:from :downfrom :upfrom)
1672           (setq start-given t)
1673           (cond ((eq prep :downfrom) (setq dir ':down))
1674                 ((eq prep :upfrom) (setq dir ':up)))
1675           (multiple-value-setq (form start-constantp start-value)
1676             (loop-constant-fold-if-possible form indexv-type))
1677           (loop-make-iteration-variable indexv form indexv-type))
1678          ((:upto :to :downto :above :below)
1679           (cond ((loop-tequal prep :upto) (setq inclusive-iteration
1680                                                 (setq dir ':up)))
1681                 ((loop-tequal prep :to) (setq inclusive-iteration t))
1682                 ((loop-tequal prep :downto) (setq inclusive-iteration
1683                                                   (setq dir ':down)))
1684                 ((loop-tequal prep :above) (setq dir ':down))
1685                 ((loop-tequal prep :below) (setq dir ':up)))
1686           (setq limit-given t)
1687           (multiple-value-setq (form limit-constantp limit-value)
1688             (loop-constant-fold-if-possible form indexv-type))
1689           (setq endform (if limit-constantp
1690                             `',limit-value
1691                             (loop-make-variable
1692                               (gensym "LOOP-LIMIT-") form indexv-type))))
1693          (:by
1694            (multiple-value-setq (form stepby-constantp stepby)
1695              (loop-constant-fold-if-possible form indexv-type))
1696            (unless stepby-constantp
1697              (loop-make-variable (setq stepby (gensym "LOOP-STEP-BY-"))
1698                                  form
1699                                  indexv-type)))
1700          (t (loop-error
1701               "~S invalid preposition in sequencing or sequence path;~@
1702                maybe invalid prepositions were specified in iteration path descriptor?"
1703               prep)))
1704        (when (and odir dir (not (eq dir odir)))
1705          (loop-error "conflicting stepping directions in LOOP sequencing path"))
1706        (setq odir dir))
1707      (when (and sequence-variable (not sequencep))
1708        (loop-error "missing OF or IN phrase in sequence path"))
1709      ;; Now fill in the defaults.
1710      (unless start-given
1711        (loop-make-iteration-variable
1712          indexv
1713          (setq start-constantp t
1714                start-value (or (loop-typed-init indexv-type) 0))
1715          indexv-type))
1716      (cond ((member dir '(nil :up))
1717             (when (or limit-given default-top)
1718               (unless limit-given
1719                 (loop-make-variable (setq endform
1720                                           (gensym "LOOP-SEQ-LIMIT-"))
1721                                     nil indexv-type)
1722                 (push `(setq ,endform ,default-top) *loop-prologue*))
1723               (setq testfn (if inclusive-iteration '> '>=)))
1724             (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1725            (t (unless start-given
1726                 (unless default-top
1727                   (loop-error "don't know where to start stepping"))
1728                 (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1729               (when (and default-top (not endform))
1730                 (setq endform (loop-typed-init indexv-type)
1731                       inclusive-iteration t))
1732               (when endform (setq testfn (if inclusive-iteration  '< '<=)))
1733               (setq step
1734                     (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1735      (when testfn
1736        (setq test
1737              `(,testfn ,indexv ,endform)))
1738      (when step-hack
1739        (setq step-hack
1740              `(,variable ,step-hack)))
1741      (let ((first-test test) (remaining-tests test))
1742        (when (and stepby-constantp start-constantp limit-constantp)
1743          (when (setq first-test
1744                      (funcall (symbol-function testfn)
1745                               start-value
1746                               limit-value))
1747            (setq remaining-tests t)))
1748        `(() (,indexv ,step)
1749          ,remaining-tests ,step-hack () () ,first-test ,step-hack))))
1750 \f
1751 ;;;; interfaces to the master sequencer
1752
1753 (defun loop-for-arithmetic (var val data-type kwd)
1754   (loop-sequencer
1755    var (loop-check-data-type data-type 'real)
1756    nil nil nil nil nil nil
1757    (loop-collect-prepositional-phrases
1758     '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1759     nil (list (list kwd val)))))
1760
1761 (defun loop-sequence-elements-path (variable data-type prep-phrases
1762                                     &key
1763                                     fetch-function
1764                                     size-function
1765                                     sequence-type
1766                                     element-type)
1767   (multiple-value-bind (indexv) (named-variable 'index)
1768     (let ((sequencev (named-variable 'sequence)))
1769       (list* nil nil                            ; dummy bindings and prologue
1770              (loop-sequencer
1771               indexv 'fixnum 
1772               variable (or data-type element-type)
1773               sequencev sequence-type
1774               `(,fetch-function ,sequencev ,indexv)
1775               `(,size-function ,sequencev)
1776               prep-phrases)))))
1777 \f
1778 ;;;; builtin LOOP iteration paths
1779
1780 #||
1781 (loop for v being the hash-values of ht do (print v))
1782 (loop for k being the hash-keys of ht do (print k))
1783 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1784 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1785 ||#
1786
1787 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
1788                                        &key (which (missing-arg)))
1789   (declare (type (member :hash-key :hash-value) which))
1790   (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1791          (loop-error "too many prepositions!"))
1792         ((null prep-phrases)
1793          (loop-error "missing OF or IN in ~S iteration path")))
1794   (let ((ht-var (gensym "LOOP-HASHTAB-"))
1795         (next-fn (gensym "LOOP-HASHTAB-NEXT-"))
1796         (dummy-predicate-var nil)
1797         (post-steps nil))
1798     (multiple-value-bind (other-var other-p)
1799         (named-variable (ecase which
1800                           (:hash-key 'hash-value)
1801                           (:hash-value 'hash-key)))
1802       ;; @@@@ NAMED-VARIABLE returns a second value of T if the name
1803       ;; was actually specified, so clever code can throw away the
1804       ;; GENSYM'ed-up variable if it isn't really needed. The
1805       ;; following is for those implementations in which we cannot put
1806       ;; dummy NILs into MULTIPLE-VALUE-SETQ variable lists.
1807       (setq other-p t
1808             dummy-predicate-var (loop-when-it-variable))
1809       (let ((key-var nil)
1810             (val-var nil)
1811             (bindings `((,variable nil ,data-type)
1812                         (,ht-var ,(cadar prep-phrases))
1813                         ,@(and other-p other-var `((,other-var nil))))))
1814         (ecase which
1815           (:hash-key (setq key-var variable
1816                            val-var (and other-p other-var)))
1817           (:hash-value (setq key-var (and other-p other-var)
1818                              val-var variable)))
1819         (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1820         (when (consp key-var)
1821           (setq post-steps
1822                 `(,key-var ,(setq key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1823                            ,@post-steps))
1824           (push `(,key-var nil) bindings))
1825         (when (consp val-var)
1826           (setq post-steps
1827                 `(,val-var ,(setq val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1828                            ,@post-steps))
1829           (push `(,val-var nil) bindings))
1830         `(,bindings                             ;bindings
1831           ()                                    ;prologue
1832           ()                                    ;pre-test
1833           ()                                    ;parallel steps
1834           (not (multiple-value-setq (,dummy-predicate-var ,key-var ,val-var)
1835                  (,next-fn)))   ;post-test
1836           ,post-steps)))))
1837
1838 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
1839                                             &key symbol-types)
1840   (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1841          (loop-error "Too many prepositions!"))
1842         ((null prep-phrases)
1843          (loop-error "missing OF or IN in ~S iteration path")))
1844   (unless (symbolp variable)
1845     (loop-error "Destructuring is not valid for package symbol iteration."))
1846   (let ((pkg-var (gensym "LOOP-PKGSYM-"))
1847         (next-fn (gensym "LOOP-PKGSYM-NEXT-")))
1848     (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types))
1849           *loop-wrappers*)
1850     `(((,variable nil ,data-type) (,pkg-var ,(cadar prep-phrases)))
1851       ()
1852       ()
1853       ()
1854       (not (multiple-value-setq (,(loop-when-it-variable)
1855                                  ,variable)
1856              (,next-fn)))
1857       ())))
1858 \f
1859 ;;;; ANSI LOOP
1860
1861 (defun make-ansi-loop-universe (extended-p)
1862   (let ((w (make-standard-loop-universe
1863              :keywords '((named (loop-do-named))
1864                          (initially (loop-do-initially))
1865                          (finally (loop-do-finally))
1866                          (do (loop-do-do))
1867                          (doing (loop-do-do))
1868                          (return (loop-do-return))
1869                          (collect (loop-list-collection list))
1870                          (collecting (loop-list-collection list))
1871                          (append (loop-list-collection append))
1872                          (appending (loop-list-collection append))
1873                          (nconc (loop-list-collection nconc))
1874                          (nconcing (loop-list-collection nconc))
1875                          (count (loop-sum-collection count
1876                                                      real
1877                                                      fixnum))
1878                          (counting (loop-sum-collection count
1879                                                         real
1880                                                         fixnum))
1881                          (sum (loop-sum-collection sum number number))
1882                          (summing (loop-sum-collection sum number number))
1883                          (maximize (loop-maxmin-collection max))
1884                          (minimize (loop-maxmin-collection min))
1885                          (maximizing (loop-maxmin-collection max))
1886                          (minimizing (loop-maxmin-collection min))
1887                          (always (loop-do-always t nil)) ; Normal, do always
1888                          (never (loop-do-always t t)) ; Negate test on always.
1889                          (thereis (loop-do-thereis t))
1890                          (while (loop-do-while nil :while)) ; Normal, do while
1891                          (until (loop-do-while t :until)) ;Negate test on while
1892                          (when (loop-do-if when nil))   ; Normal, do when
1893                          (if (loop-do-if if nil))       ; synonymous
1894                          (unless (loop-do-if unless t)) ; Negate test on when
1895                          (with (loop-do-with)))
1896              :for-keywords '((= (loop-ansi-for-equals))
1897                              (across (loop-for-across))
1898                              (in (loop-for-in))
1899                              (on (loop-for-on))
1900                              (from (loop-for-arithmetic :from))
1901                              (downfrom (loop-for-arithmetic :downfrom))
1902                              (upfrom (loop-for-arithmetic :upfrom))
1903                              (below (loop-for-arithmetic :below))
1904                              (to (loop-for-arithmetic :to))
1905                              (upto (loop-for-arithmetic :upto))
1906                              (by (loop-for-arithmetic :by))
1907                              (being (loop-for-being)))
1908              :iteration-keywords '((for (loop-do-for))
1909                                    (as (loop-do-for))
1910                                    (repeat (loop-do-repeat)))
1911              :type-symbols '(array atom bignum bit bit-vector character
1912                              compiled-function complex cons double-float
1913                              fixnum float function hash-table integer
1914                              keyword list long-float nil null number
1915                              package pathname random-state ratio rational
1916                              readtable sequence short-float simple-array
1917                              simple-bit-vector simple-string simple-vector
1918                              single-float standard-char stream string
1919                              base-char symbol t vector)
1920              :type-keywords nil
1921              :ansi (if extended-p :extended t))))
1922     (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
1923                    :preposition-groups '((:of :in))
1924                    :inclusive-permitted nil
1925                    :user-data '(:which :hash-key))
1926     (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
1927                    :preposition-groups '((:of :in))
1928                    :inclusive-permitted nil
1929                    :user-data '(:which :hash-value))
1930     (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
1931                    :preposition-groups '((:of :in))
1932                    :inclusive-permitted nil
1933                    :user-data '(:symbol-types (:internal
1934                                                :external
1935                                                :inherited)))
1936     (add-loop-path '(external-symbol external-symbols)
1937                    'loop-package-symbols-iteration-path w
1938                    :preposition-groups '((:of :in))
1939                    :inclusive-permitted nil
1940                    :user-data '(:symbol-types (:external)))
1941     (add-loop-path '(present-symbol present-symbols)
1942                    'loop-package-symbols-iteration-path w
1943                    :preposition-groups '((:of :in))
1944                    :inclusive-permitted nil
1945                    :user-data '(:symbol-types (:internal
1946                                                :external)))
1947     w))
1948
1949 (defparameter *loop-ansi-universe*
1950   (make-ansi-loop-universe nil))
1951
1952 (defun loop-standard-expansion (keywords-and-forms environment universe)
1953   (if (and keywords-and-forms (symbolp (car keywords-and-forms)))
1954     (loop-translate keywords-and-forms environment universe)
1955     (let ((tag (gensym)))
1956       `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
1957
1958 (sb!int:defmacro-mundanely loop (&environment env &rest keywords-and-forms)
1959   (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))
1960
1961 (sb!int:defmacro-mundanely loop-finish ()
1962   #!+sb-doc
1963   "Cause the iteration to terminate \"normally\", the same as implicit
1964 termination by an iteration driving clause, or by use of WHILE or
1965 UNTIL -- the epilogue code (if any) will be run, and any implicitly
1966 collected result will be returned as the value of the LOOP."
1967   '(go end-loop))