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