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