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