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