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