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