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