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