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