0.6.12.49:
[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 #'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
506 ;;;*loop-variables*.
507 (defvar *loop-declarations*)
508
509 ;;;Used by LOOP for destructuring binding, if it is doing that itself.
510 ;;; See loop-make-variable.
511 (defvar *loop-desetq-crocks*)
512
513 ;;; List of wrapping forms, innermost first, which go immediately inside
514 ;;; the current set of parallel bindings being accumulated in
515 ;;; *loop-variables*. The wrappers are appended onto a body. E.g.,
516 ;;; this list could conceivably has as its value ((with-open-file (g0001
517 ;;; g0002 ...))), with g0002 being one of the bindings in
518 ;;; *loop-variables* (this is why the wrappers go inside of the variable
519 ;;; bindings).
520 (defvar *loop-wrappers*)
521
522 ;;;This accumulates lists of previous values of *loop-variables* and the
523 ;;;other lists  above, for each new nesting of bindings. See
524 ;;;loop-bind-block.
525 (defvar *loop-bind-stack*)
526
527 ;;;This is a LOOP-global variable for the (obsolete) NODECLARE clause
528 ;;;which inhibits  LOOP from actually outputting a type declaration for
529 ;;;an iteration (or any) variable.
530 (defvar *loop-nodeclare*)
531
532 ;;;This is simply a list of LOOP iteration variables, used for checking
533 ;;;for duplications.
534 (defvar *loop-iteration-variables*)
535
536 ;;;List of prologue forms of the loop, accumulated in reverse order.
537 (defvar *loop-prologue*)
538
539 (defvar *loop-before-loop*)
540 (defvar *loop-body*)
541 (defvar *loop-after-body*)
542
543 ;;;This is T if we have emitted any body code, so that iteration driving
544 ;;;clauses can be disallowed. This is not strictly the same as
545 ;;;checking *loop-body*, because we permit some clauses  such as RETURN
546 ;;;to not be considered "real" body (so as to permit the user to "code"
547 ;;;an  abnormal return value "in loop").
548 (defvar *loop-emitted-body*)
549
550 ;;;List of epilogue forms (supplied by FINALLY generally), accumulated
551 ;;; in reverse order.
552 (defvar *loop-epilogue*)
553
554 ;;;List of epilogue forms which are supplied after the above "user"
555 ;;;epilogue. "normal" termination return values are provide by putting
556 ;;;the return form in here. Normally this is done using
557 ;;;loop-emit-final-value, q.v.
558 (defvar *loop-after-epilogue*)
559
560 ;;;The "culprit" responsible for supplying a final value from the loop.
561 ;;;This  is so loop-emit-final-value can moan about multiple return
562 ;;;values being supplied.
563 (defvar *loop-final-value-culprit*)
564
565 ;;;If not NIL, we are in some branch of a conditional. Some clauses may
566 ;;;be disallowed.
567 (defvar *loop-inside-conditional*)
568
569 ;;;If not NIL, this is a temporary bound around the loop for holding the
570 ;;;temporary  value for "it" in things like "when (f) collect it". It
571 ;;;may be used as a supertemporary by some other things.
572 (defvar *loop-when-it-variable*)
573
574 ;;;Sometimes we decide we need to fold together parts of the loop, but
575 ;;;some part of the generated iteration  code is different for the first
576 ;;;and remaining iterations. This variable will be the temporary which
577 ;;;is the flag used in the loop to tell whether we are in the first or
578 ;;;remaining iterations.
579 (defvar *loop-never-stepped-variable*)
580
581 ;;;List of all the value-accumulation descriptor structures in the loop.
582 ;;; See loop-get-collection-info.
583 (defvar *loop-collection-cruft*)                ; for multiple COLLECTs (etc)
584 \f
585 ;;;; code analysis stuff
586
587 (defun loop-constant-fold-if-possible (form &optional expected-type)
588   (let ((new-form form) (constantp nil) (constant-value nil))
589     (when (setq constantp (constantp new-form))
590       (setq constant-value (eval new-form)))
591     (when (and constantp expected-type)
592       (unless (typep constant-value expected-type)
593         (loop-warn "The form ~S evaluated to ~S, which was not of the anticipated type ~S."
594                    form constant-value expected-type)
595         (setq constantp nil constant-value nil)))
596     (values new-form constantp constant-value)))
597
598 (defun loop-constantp (form)
599   (constantp form))
600 \f
601 ;;;; LOOP iteration optimization
602
603 (defvar *loop-duplicate-code*
604         nil)
605
606 (defvar *loop-iteration-flag-variable*
607         (make-symbol "LOOP-NOT-FIRST-TIME"))
608
609 (defun loop-code-duplication-threshold (env)
610   (declare (ignore env))
611   (let (;; If we could read optimization declaration information (as with
612         ;; the DECLARATION-INFORMATION function (present in CLTL2, removed
613         ;; from ANSI standard) we could set these values flexibly. Without
614         ;; DECLARATION-INFORMATION, we have to set them to constants.
615         (speed 1)
616         (space 1))
617     (+ 40 (* (- speed space) 10))))
618
619 (sb!int:defmacro-mundanely loop-body (&environment env
620                                          prologue
621                                          before-loop
622                                          main-body
623                                          after-loop
624                                          epilogue
625                                          &aux rbefore rafter flagvar)
626   (unless (= (length before-loop) (length after-loop))
627     (error "LOOP-BODY called with non-synched before- and after-loop lists"))
628   ;;All our work is done from these copies, working backwards from the end:
629   (setq rbefore (reverse before-loop) rafter (reverse after-loop))
630   (labels ((psimp (l)
631              (let ((ans nil))
632                (dolist (x l)
633                  (when x
634                    (push x ans)
635                    (when (and (consp x)
636                               (member (car x) '(go return return-from)))
637                      (return nil))))
638                (nreverse ans)))
639            (pify (l) (if (null (cdr l)) (car l) `(progn ,@l)))
640            (makebody ()
641              (let ((form `(tagbody
642                             ,@(psimp (append prologue (nreverse rbefore)))
643                          next-loop
644                             ,@(psimp (append main-body
645                                              (nreconc rafter
646                                                       `((go next-loop)))))
647                          end-loop
648                             ,@(psimp epilogue))))
649                (if flagvar `(let ((,flagvar nil)) ,form) form))))
650     (when (or *loop-duplicate-code* (not rbefore))
651       (return-from loop-body (makebody)))
652     ;; This outer loop iterates once for each not-first-time flag test
653     ;; generated plus once more for the forms that don't need a flag test
654     (do ((threshold (loop-code-duplication-threshold env))) (nil)
655       (declare (fixnum threshold))
656       ;; Go backwards from the ends of before-loop and after-loop merging all
657       ;; the equivalent forms into the body.
658       (do () ((or (null rbefore) (not (equal (car rbefore) (car rafter)))))
659         (push (pop rbefore) main-body)
660         (pop rafter))
661       (unless rbefore (return (makebody)))
662       ;; The first forms in rbefore & rafter (which are the chronologically
663       ;; last forms in the list) differ, therefore they cannot be moved
664       ;; into the main body. If everything that chronologically precedes
665       ;; them either differs or is equal but is okay to duplicate, we can
666       ;; just put all of rbefore in the prologue and all of rafter after
667       ;; the body. Otherwise, there is something that is not okay to
668       ;; duplicate, so it and everything chronologically after it in
669       ;; rbefore and rafter must go into the body, with a flag test to
670       ;; distinguish the first time around the loop from later times.
671       ;; What chronologically precedes the non-duplicatable form will
672       ;; be handled the next time around the outer loop.
673       (do ((bb rbefore (cdr bb))
674            (aa rafter (cdr aa))
675            (lastdiff nil)
676            (count 0)
677            (inc nil))
678           ((null bb) (return-from loop-body (makebody)))        ; Did it.
679         (cond ((not (equal (car bb) (car aa))) (setq lastdiff bb count 0))
680               ((or (not (setq inc (estimate-code-size (car bb) env)))
681                    (> (incf count inc) threshold))
682                ;; Ok, we have found a non-duplicatable piece of code.
683                ;; Everything chronologically after it must be in the central
684                ;; body. Everything chronologically at and after lastdiff goes
685                ;; into the central body under a flag test.
686                (let ((then nil) (else nil))
687                  (do () (nil)
688                    (push (pop rbefore) else)
689                    (push (pop rafter) then)
690                    (when (eq rbefore (cdr lastdiff)) (return)))
691                  (unless flagvar
692                    (push `(setq ,(setq flagvar *loop-iteration-flag-variable*)
693                                 t)
694                          else))
695                  (push `(if ,flagvar ,(pify (psimp then)) ,(pify (psimp else)))
696                        main-body))
697                ;; Everything chronologically before lastdiff until the
698                ;; non-duplicatable form (car bb) is the same in rbefore and
699                ;; rafter so just copy it into the body
700                (do () (nil)
701                  (pop rafter)
702                  (push (pop rbefore) main-body)
703                  (when (eq rbefore (cdr bb)) (return)))
704                (return)))))))
705 \f
706 (defun duplicatable-code-p (expr env)
707   (if (null expr) 0
708       (let ((ans (estimate-code-size expr env)))
709         (declare (fixnum ans))
710         ;; @@@@ Use (DECLARATION-INFORMATION 'OPTIMIZE ENV) here to get an
711         ;; alist of optimize quantities back to help quantify how much code we
712         ;; are willing to duplicate.
713         ans)))
714
715 (defvar *special-code-sizes*
716         '((return 0) (progn 0)
717           (null 1) (not 1) (eq 1) (car 1) (cdr 1)
718           (when 1) (unless 1) (if 1)
719           (caar 2) (cadr 2) (cdar 2) (cddr 2)
720           (caaar 3) (caadr 3) (cadar 3) (caddr 3)
721           (cdaar 3) (cdadr 3) (cddar 3) (cdddr 3)
722           (caaaar 4) (caaadr 4) (caadar 4) (caaddr 4)
723           (cadaar 4) (cadadr 4) (caddar 4) (cadddr 4)
724           (cdaaar 4) (cdaadr 4) (cdadar 4) (cdaddr 4)
725           (cddaar 4) (cddadr 4) (cdddar 4) (cddddr 4)))
726
727 (defvar *estimate-code-size-punt*
728         '(block
729            do do* dolist
730            flet
731            labels lambda let let* locally
732            macrolet multiple-value-bind
733            prog prog*
734            symbol-macrolet
735            tagbody
736            unwind-protect
737            with-open-file))
738
739 (defun destructuring-size (x)
740   (do ((x x (cdr x)) (n 0 (+ (destructuring-size (car x)) n)))
741       ((atom x) (+ n (if (null x) 0 1)))))
742
743 (defun estimate-code-size (x env)
744   (catch 'estimate-code-size
745     (estimate-code-size-1 x env)))
746
747 (defun estimate-code-size-1 (x env)
748   (flet ((list-size (l)
749            (let ((n 0))
750              (declare (fixnum n))
751              (dolist (x l n) (incf n (estimate-code-size-1 x env))))))
752     ;;@@@@ ???? (declare (function list-size (list) fixnum))
753     (cond ((constantp x) 1)
754           ((symbolp x) (multiple-value-bind (new-form expanded-p)
755                            (sb!xc:macroexpand-1 x env)
756                          (if expanded-p
757                              (estimate-code-size-1 new-form env)
758                              1)))
759           ((atom x) 1) ;; ??? self-evaluating???
760           ((symbolp (car x))
761            (let ((fn (car x)) (tem nil) (n 0))
762              (declare (symbol fn) (fixnum n))
763              (macrolet ((f (overhead &optional (args nil args-p))
764                           `(the fixnum (+ (the fixnum ,overhead)
765                                           (the fixnum
766                                                (list-size ,(if args-p
767                                                                args
768                                                              '(cdr x))))))))
769                (cond ((setq tem (get fn 'estimate-code-size))
770                       (typecase tem
771                         (fixnum (f tem))
772                         (t (funcall tem x env))))
773                      ((setq tem (assoc fn *special-code-sizes*))
774                       (f (second tem)))
775                      ((eq fn 'cond)
776                       (dolist (clause (cdr x) n)
777                         (incf n (list-size clause)) (incf n)))
778                      ((eq fn 'desetq)
779                       (do ((l (cdr x) (cdr l))) ((null l) n)
780                         (setq n (+ n
781                                    (destructuring-size (car l))
782                                    (estimate-code-size-1 (cadr l) env)))))
783                      ((member fn '(setq psetq))
784                       (do ((l (cdr x) (cdr l))) ((null l) n)
785                         (setq n (+ n (estimate-code-size-1 (cadr l) env) 1))))
786                      ((eq fn 'go) 1)
787                      ((eq fn 'function)
788                       ;; This skirts the issue of implementationally-defined
789                       ;; lambda macros by recognizing CL function names and
790                       ;; nothing else.
791                       (if (or (symbolp (cadr x))
792                               (and (consp (cadr x)) (eq (caadr x) 'setf)))
793                           1
794                           (throw 'duplicatable-code-p nil)))
795                      ((eq fn 'multiple-value-setq)
796                       (f (length (second x)) (cddr x)))
797                      ((eq fn 'return-from)
798                       (1+ (estimate-code-size-1 (third x) env)))
799                      ((or (special-operator-p fn)
800                           (member fn *estimate-code-size-punt*))
801                       (throw 'estimate-code-size nil))
802                      (t (multiple-value-bind (new-form expanded-p)
803                             (sb!xc:macroexpand-1 x env)
804                           (if expanded-p
805                               (estimate-code-size-1 new-form env)
806                               (f 3))))))))
807           (t (throw 'estimate-code-size nil)))))
808 \f
809 ;;;; loop errors
810
811 (defun loop-context ()
812   (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
813       ((eq l (cdr *loop-source-code*)) (nreverse new))))
814
815 (defun loop-error (format-string &rest format-args)
816   (error "~?~%current LOOP context:~{ ~S~}."
817          format-string
818          format-args
819          (loop-context)))
820
821 (defun loop-warn (format-string &rest format-args)
822   (warn "~?~%current LOOP context:~{ ~S~}."
823         format-string
824         format-args
825         (loop-context)))
826
827 (defun loop-check-data-type (specified-type required-type
828                              &optional (default-type required-type))
829   (if (null specified-type)
830       default-type
831       (multiple-value-bind (a b) (subtypep specified-type required-type)
832         (cond ((not b)
833                (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
834                           specified-type required-type))
835               ((not a)
836                (loop-error "The specified data type ~S is not a subtype of ~S."
837                            specified-type required-type)))
838         specified-type)))
839 \f
840 (defun loop-translate (*loop-source-code*
841                        *loop-macro-environment*
842                        *loop-universe*)
843   (let ((*loop-original-source-code* *loop-source-code*)
844         (*loop-source-context* nil)
845         (*loop-iteration-variables* nil)
846         (*loop-variables* nil)
847         (*loop-nodeclare* nil)
848         (*loop-named-variables* nil)
849         (*loop-declarations* nil)
850         (*loop-desetq-crocks* nil)
851         (*loop-bind-stack* nil)
852         (*loop-prologue* nil)
853         (*loop-wrappers* nil)
854         (*loop-before-loop* nil)
855         (*loop-body* nil)
856         (*loop-emitted-body* nil)
857         (*loop-after-body* nil)
858         (*loop-epilogue* nil)
859         (*loop-after-epilogue* nil)
860         (*loop-final-value-culprit* nil)
861         (*loop-inside-conditional* nil)
862         (*loop-when-it-variable* nil)
863         (*loop-never-stepped-variable* nil)
864         (*loop-names* nil)
865         (*loop-collection-cruft* nil))
866     (loop-iteration-driver)
867     (loop-bind-block)
868     (let ((answer `(loop-body
869                      ,(nreverse *loop-prologue*)
870                      ,(nreverse *loop-before-loop*)
871                      ,(nreverse *loop-body*)
872                      ,(nreverse *loop-after-body*)
873                      ,(nreconc *loop-epilogue*
874                                (nreverse *loop-after-epilogue*)))))
875       (do () (nil)
876         (setq answer `(block ,(pop *loop-names*) ,answer))
877         (unless *loop-names* (return nil)))
878       (dolist (entry *loop-bind-stack*)
879         (let ((vars (first entry))
880               (dcls (second entry))
881               (crocks (third entry))
882               (wrappers (fourth entry)))
883           (dolist (w wrappers)
884             (setq answer (append w (list answer))))
885           (when (or vars dcls crocks)
886             (let ((forms (list answer)))
887               ;;(when crocks (push crocks forms))
888               (when dcls (push `(declare ,@dcls) forms))
889               (setq answer `(,(cond ((not vars) 'locally)
890                                     (*loop-destructuring-hooks*
891                                      (first *loop-destructuring-hooks*))
892                                     (t
893                                      'let))
894                              ,vars
895                              ,@(if crocks
896                                    `((destructuring-bind ,@crocks
897                                          ,@forms))
898                                  forms)))))))
899       answer)))
900
901 (defun loop-iteration-driver ()
902   (do () ((null *loop-source-code*))
903     (let ((keyword (car *loop-source-code*)) (tem nil))
904       (cond ((not (symbolp keyword))
905              (loop-error "~S found where LOOP keyword expected" keyword))
906             (t (setq *loop-source-context* *loop-source-code*)
907                (loop-pop-source)
908                (cond ((setq tem
909                             (loop-lookup-keyword keyword
910                                                  (loop-universe-keywords
911                                                   *loop-universe*)))
912                       ;; It's a "miscellaneous" toplevel LOOP keyword (DO,
913                       ;; COLLECT, NAMED, etc.)
914                       (apply (symbol-function (first tem)) (rest tem)))
915                      ((setq tem
916                             (loop-lookup-keyword keyword
917                                                  (loop-universe-iteration-keywords *loop-universe*)))
918                       (loop-hack-iteration tem))
919                      ((loop-tmember keyword '(and else))
920                       ;; The alternative is to ignore it, i.e. let it go
921                       ;; around to the next keyword...
922                       (loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
923                                   keyword
924                                   (car *loop-source-code*)
925                                   (cadr *loop-source-code*)))
926                      (t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
927 \f
928 (defun loop-pop-source ()
929   (if *loop-source-code*
930       (pop *loop-source-code*)
931       (loop-error "LOOP source code ran out when another token was expected.")))
932
933 (defun loop-get-progn ()
934   (do ((forms (list (loop-pop-source)) (cons (loop-pop-source) forms))
935        (nextform (car *loop-source-code*) (car *loop-source-code*)))
936       ((atom nextform)
937        (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
938
939 (defun loop-get-form ()
940   (if *loop-source-code*
941       (loop-pop-source)
942       (loop-error "LOOP code ran out where a form was expected.")))
943
944 (defun loop-construct-return (form)
945   `(return-from ,(car *loop-names*) ,form))
946
947 (defun loop-pseudo-body (form)
948   (cond ((or *loop-emitted-body* *loop-inside-conditional*)
949          (push form *loop-body*))
950         (t (push form *loop-before-loop*) (push form *loop-after-body*))))
951
952 (defun loop-emit-body (form)
953   (setq *loop-emitted-body* t)
954   (loop-pseudo-body form))
955
956 (defun loop-emit-final-value (form)
957   (push (loop-construct-return form) *loop-after-epilogue*)
958   (when *loop-final-value-culprit*
959     (loop-warn "The LOOP clause is providing a value for the iteration,~@
960                 however one was already established by a ~S clause."
961                *loop-final-value-culprit*))
962   (setq *loop-final-value-culprit* (car *loop-source-context*)))
963
964 (defun loop-disallow-conditional (&optional kwd)
965   (when *loop-inside-conditional*
966     (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
967 \f
968 ;;;; loop types
969
970 (defun loop-typed-init (data-type)
971   (when (and data-type (subtypep data-type 'number))
972     (if (or (subtypep data-type 'float) (subtypep data-type '(complex float)))
973         (coerce 0 data-type)
974         0)))
975
976 (defun loop-optional-type (&optional variable)
977   ;; No variable specified implies that no destructuring is permissible.
978   (and *loop-source-code* ; Don't get confused by NILs..
979        (let ((z (car *loop-source-code*)))
980          (cond ((loop-tequal z 'of-type)
981                 ;; This is the syntactically unambigous form in that the form
982                 ;; of the type specifier does not matter. Also, it is assumed
983                 ;; that the type specifier is unambiguously, and without need
984                 ;; of translation, a common lisp type specifier or pattern
985                 ;; (matching the variable) thereof.
986                 (loop-pop-source)
987                 (loop-pop-source))
988
989                ((symbolp z)
990                 ;; This is the (sort of) "old" syntax, even though we didn't
991                 ;; used to support all of these type symbols.
992                 (let ((type-spec (or (gethash z
993                                               (loop-universe-type-symbols
994                                                *loop-universe*))
995                                      (gethash (symbol-name z)
996                                               (loop-universe-type-keywords
997                                                *loop-universe*)))))
998                   (when type-spec
999                     (loop-pop-source)
1000                     type-spec)))
1001                (t
1002                 ;; This is our sort-of old syntax. But this is only valid for
1003                 ;; when we are destructuring, so we will be compulsive (should
1004                 ;; we really be?) and require that we in fact be doing variable
1005                 ;; destructuring here. We must translate the old keyword
1006                 ;; pattern typespec into a fully-specified pattern of real type
1007                 ;; specifiers here.
1008                 (if (consp variable)
1009                     (unless (consp z)
1010                      (loop-error
1011                         "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
1012                         z))
1013                     (loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
1014                 (loop-pop-source)
1015                 (labels ((translate (k v)
1016                            (cond ((null k) nil)
1017                                  ((atom k)
1018                                   (replicate
1019                                     (or (gethash k
1020                                                  (loop-universe-type-symbols
1021                                                   *loop-universe*))
1022                                         (gethash (symbol-name k)
1023                                                  (loop-universe-type-keywords
1024                                                   *loop-universe*))
1025                                         (loop-error
1026                                           "The destructuring type pattern ~S contains the unrecognized type keyword ~S."
1027                                           z k))
1028                                     v))
1029                                  ((atom v)
1030                                   (loop-error
1031                                     "The destructuring type pattern ~S doesn't match the variable pattern ~S."
1032                                     z variable))
1033                                  (t (cons (translate (car k) (car v))
1034                                           (translate (cdr k) (cdr v))))))
1035                          (replicate (typ v)
1036                            (if (atom v)
1037                                typ
1038                                (cons (replicate typ (car v))
1039                                      (replicate typ (cdr v))))))
1040                   (translate z variable)))))))
1041 \f
1042 ;;;; loop variables
1043
1044 (defun loop-bind-block ()
1045   (when (or *loop-variables* *loop-declarations* *loop-wrappers*)
1046     (push (list (nreverse *loop-variables*)
1047                 *loop-declarations*
1048                 *loop-desetq-crocks*
1049                 *loop-wrappers*)
1050           *loop-bind-stack*)
1051     (setq *loop-variables* nil
1052           *loop-declarations* nil
1053           *loop-desetq-crocks* nil
1054           *loop-wrappers* nil)))
1055
1056 (defun loop-make-variable (name initialization dtype
1057                            &optional iteration-variable-p)
1058   (cond ((null name)
1059          (cond ((not (null initialization))
1060                 (push (list (setq name (loop-gentemp 'loop-ignore-))
1061                             initialization)
1062                       *loop-variables*)
1063                 (push `(ignore ,name) *loop-declarations*))))
1064         ((atom name)
1065          (cond (iteration-variable-p
1066                 (if (member name *loop-iteration-variables*)
1067                     (loop-error "duplicated LOOP iteration variable ~S" name)
1068                     (push name *loop-iteration-variables*)))
1069                ((assoc name *loop-variables*)
1070                 (loop-error "duplicated variable ~S in LOOP parallel binding"
1071                             name)))
1072          (unless (symbolp name)
1073            (loop-error "bad variable ~S somewhere in LOOP" name))
1074          (loop-declare-variable name dtype)
1075          ;; We use ASSOC on this list to check for duplications (above),
1076          ;; so don't optimize out this list:
1077          (push (list name (or initialization (loop-typed-init dtype)))
1078                *loop-variables*))
1079         (initialization
1080          (cond (*loop-destructuring-hooks*
1081                 (loop-declare-variable name dtype)
1082                 (push (list name initialization) *loop-variables*))
1083                (t (let ((newvar (loop-gentemp 'loop-destructure-)))
1084                     (push (list newvar initialization) *loop-variables*)
1085                     ;; *LOOP-DESETQ-CROCKS* gathered in reverse order.
1086                     (setq *loop-desetq-crocks*
1087                       (list* name newvar *loop-desetq-crocks*))
1088                     ;; FIXME: We can delete this, right?
1089                     #+ignore
1090                     (loop-make-variable name
1091                                         nil
1092                                         dtype
1093                                         iteration-variable-p)))))
1094         (t (let ((tcar nil) (tcdr nil))
1095              (if (atom dtype) (setq tcar (setq tcdr dtype))
1096                  (setq tcar (car dtype) tcdr (cdr dtype)))
1097              (loop-make-variable (car name) nil tcar iteration-variable-p)
1098              (loop-make-variable (cdr name) nil tcdr iteration-variable-p))))
1099   name)
1100
1101 (defun loop-make-iteration-variable (name initialization dtype)
1102   (loop-make-variable name initialization dtype t))
1103
1104 (defun loop-declare-variable (name dtype)
1105   (cond ((or (null name) (null dtype) (eq dtype t)) nil)
1106         ((symbolp name)
1107          (unless (or (eq dtype t) (member (the symbol name) *loop-nodeclare*))
1108            (let ((dtype (let ((init (loop-typed-init dtype)))
1109                           (if (typep init dtype)
1110                             dtype
1111                             `(or (member ,init) ,dtype)))))
1112              (push `(type ,dtype ,name) *loop-declarations*))))
1113         ((consp name)
1114          (cond ((consp dtype)
1115                 (loop-declare-variable (car name) (car dtype))
1116                 (loop-declare-variable (cdr name) (cdr dtype)))
1117                (t (loop-declare-variable (car name) dtype)
1118                   (loop-declare-variable (cdr name) dtype))))
1119         (t (error "invalid LOOP variable passed in: ~S" name))))
1120
1121 (defun loop-maybe-bind-form (form data-type)
1122   (if (loop-constantp form)
1123       form
1124       (loop-make-variable (loop-gentemp 'loop-bind-) form data-type)))
1125 \f
1126 (defun loop-do-if (for negatep)
1127   (let ((form (loop-get-form)) (*loop-inside-conditional* t) (it-p nil))
1128     (flet ((get-clause (for)
1129              (do ((body nil)) (nil)
1130                (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
1131                  (cond ((not (symbolp key))
1132                         (loop-error
1133                           "~S found where keyword expected getting LOOP clause after ~S"
1134                           key for))
1135                        (t (setq *loop-source-context* *loop-source-code*)
1136                           (loop-pop-source)
1137                           (when (loop-tequal (car *loop-source-code*) 'it)
1138                             (setq *loop-source-code*
1139                                   (cons (or it-p
1140                                             (setq it-p
1141                                                   (loop-when-it-variable)))
1142                                         (cdr *loop-source-code*))))
1143                           (cond ((or (not (setq data (loop-lookup-keyword
1144                                                        key (loop-universe-keywords *loop-universe*))))
1145                                      (progn (apply (symbol-function (car data))
1146                                                    (cdr data))
1147                                             (null *loop-body*)))
1148                                  (loop-error
1149                                    "~S does not introduce a LOOP clause that can follow ~S."
1150                                    key for))
1151                                 (t (setq body (nreconc *loop-body* body)))))))
1152                (if (loop-tequal (car *loop-source-code*) :and)
1153                    (loop-pop-source)
1154                    (return (if (cdr body)
1155                                `(progn ,@(nreverse body))
1156                                (car body)))))))
1157       (let ((then (get-clause for))
1158             (else (when (loop-tequal (car *loop-source-code*) :else)
1159                     (loop-pop-source)
1160                     (list (get-clause :else)))))
1161         (when (loop-tequal (car *loop-source-code*) :end)
1162           (loop-pop-source))
1163         (when it-p (setq form `(setq ,it-p ,form)))
1164         (loop-pseudo-body
1165           `(if ,(if negatep `(not ,form) form)
1166                ,then
1167                ,@else))))))
1168
1169 (defun loop-do-initially ()
1170   (loop-disallow-conditional :initially)
1171   (push (loop-get-progn) *loop-prologue*))
1172
1173 (defun loop-do-finally ()
1174   (loop-disallow-conditional :finally)
1175   (push (loop-get-progn) *loop-epilogue*))
1176
1177 (defun loop-do-do ()
1178   (loop-emit-body (loop-get-progn)))
1179
1180 (defun loop-do-named ()
1181   (let ((name (loop-pop-source)))
1182     (unless (symbolp name)
1183       (loop-error "~S is an invalid name for your LOOP" name))
1184     (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1185       (loop-error "The NAMED ~S clause occurs too late." name))
1186     (when *loop-names*
1187       (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1188                   (car *loop-names*) name))
1189     (setq *loop-names* (list name nil))))
1190
1191 (defun loop-do-return ()
1192   (loop-pseudo-body (loop-construct-return (loop-get-form))))
1193 \f
1194 ;;;; value accumulation: LIST
1195
1196 (defstruct (loop-collector
1197             (:copier nil)
1198             (:predicate nil))
1199   name
1200   class
1201   (history nil)
1202   (tempvars nil)
1203   dtype
1204   (data nil)) ;collector-specific data
1205
1206 (defun loop-get-collection-info (collector class default-type)
1207   (let ((form (loop-get-form))
1208         (dtype (and (not (loop-universe-ansi *loop-universe*)) (loop-optional-type)))
1209         (name (when (loop-tequal (car *loop-source-code*) 'into)
1210                 (loop-pop-source)
1211                 (loop-pop-source))))
1212     (when (not (symbolp name))
1213       (loop-error "The value accumulation recipient name, ~S, is not a symbol." name))
1214     (unless dtype
1215       (setq dtype (or (loop-optional-type) default-type)))
1216     (let ((cruft (find (the symbol name) *loop-collection-cruft*
1217                        :key #'loop-collector-name)))
1218       (cond ((not cruft)
1219              (push (setq cruft (make-loop-collector
1220                                  :name name :class class
1221                                  :history (list collector) :dtype dtype))
1222                    *loop-collection-cruft*))
1223             (t (unless (eq (loop-collector-class cruft) class)
1224                  (loop-error
1225                    "incompatible kinds of LOOP value accumulation specified for collecting~@
1226                     ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S"
1227                    name (car (loop-collector-history cruft)) collector))
1228                (unless (equal dtype (loop-collector-dtype cruft))
1229                  (loop-warn
1230                    "unequal datatypes specified in different LOOP value accumulations~@
1231                    into ~S: ~S and ~S"
1232                    name dtype (loop-collector-dtype cruft))
1233                  (when (eq (loop-collector-dtype cruft) t)
1234                    (setf (loop-collector-dtype cruft) dtype)))
1235                (push collector (loop-collector-history cruft))))
1236       (values cruft form))))
1237
1238 (defun loop-list-collection (specifically)      ; NCONC, LIST, or APPEND
1239   (multiple-value-bind (lc form)
1240       (loop-get-collection-info specifically 'list 'list)
1241     (let ((tempvars (loop-collector-tempvars lc)))
1242       (unless tempvars
1243         (setf (loop-collector-tempvars lc)
1244               (setq tempvars (list* (loop-gentemp 'loop-list-head-)
1245                                     (loop-gentemp 'loop-list-tail-)
1246                                     (and (loop-collector-name lc)
1247                                          (list (loop-collector-name lc))))))
1248         (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1249         (unless (loop-collector-name lc)
1250           (loop-emit-final-value `(loop-collect-answer ,(car tempvars)
1251                                                        ,@(cddr tempvars)))))
1252       (ecase specifically
1253         (list (setq form `(list ,form)))
1254         (nconc nil)
1255         (append (unless (and (consp form) (eq (car form) 'list))
1256                   (setq form `(copy-list ,form)))))
1257       (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1258 \f
1259 ;;;; value accumulation: MAX, MIN, SUM, COUNT
1260
1261 (defun loop-sum-collection (specifically required-type default-type);SUM, COUNT
1262   (multiple-value-bind (lc form)
1263       (loop-get-collection-info specifically 'sum default-type)
1264     (loop-check-data-type (loop-collector-dtype lc) required-type)
1265     (let ((tempvars (loop-collector-tempvars lc)))
1266       (unless tempvars
1267         (setf (loop-collector-tempvars lc)
1268               (setq tempvars (list (loop-make-variable
1269                                      (or (loop-collector-name lc)
1270                                          (loop-gentemp 'loop-sum-))
1271                                      nil (loop-collector-dtype lc)))))
1272         (unless (loop-collector-name lc)
1273           (loop-emit-final-value (car (loop-collector-tempvars lc)))))
1274       (loop-emit-body
1275         (if (eq specifically 'count)
1276             `(when ,form
1277                (setq ,(car tempvars)
1278                      ,(hide-variable-reference t
1279                                                (car tempvars)
1280                                                `(1+ ,(car tempvars)))))
1281             `(setq ,(car tempvars)
1282                    (+ ,(hide-variable-reference t
1283                                                 (car tempvars)
1284                                                 (car tempvars))
1285                       ,form)))))))
1286
1287 (defun loop-maxmin-collection (specifically)
1288   (multiple-value-bind (lc form)
1289       (loop-get-collection-info specifically 'maxmin *loop-real-data-type*)
1290     (loop-check-data-type (loop-collector-dtype lc) *loop-real-data-type*)
1291     (let ((data (loop-collector-data lc)))
1292       (unless data
1293         (setf (loop-collector-data lc)
1294               (setq data (make-loop-minimax
1295                            (or (loop-collector-name lc)
1296                                (loop-gentemp 'loop-maxmin-))
1297                            (loop-collector-dtype lc))))
1298         (unless (loop-collector-name lc)
1299           (loop-emit-final-value (loop-minimax-answer-variable data))))
1300       (loop-note-minimax-operation specifically data)
1301       (push `(with-minimax-value ,data) *loop-wrappers*)
1302       (loop-emit-body `(loop-accumulate-minimax-value ,data
1303                                                       ,specifically
1304                                                       ,form)))))
1305 \f
1306 ;;;; value accumulation: aggregate booleans
1307
1308 ;;; handling the ALWAYS and NEVER loop keywords
1309 ;;;
1310 ;;; Under ANSI these are not permitted to appear under conditionalization.
1311 (defun loop-do-always (restrictive negate)
1312   (let ((form (loop-get-form)))
1313     (when restrictive (loop-disallow-conditional))
1314     (loop-emit-body `(,(if negate 'when 'unless) ,form
1315                       ,(loop-construct-return nil)))
1316     (loop-emit-final-value t)))
1317
1318 ;;; handling the THEREIS loop keyword
1319 ;;;
1320 ;;; Under ANSI this is not permitted to appear under conditionalization.
1321 (defun loop-do-thereis (restrictive)
1322   (when restrictive (loop-disallow-conditional))
1323   (loop-emit-body `(when (setq ,(loop-when-it-variable) ,(loop-get-form))
1324                      ,(loop-construct-return *loop-when-it-variable*))))
1325 \f
1326 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1327   (loop-disallow-conditional kwd)
1328   (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1329
1330 (defun loop-do-with ()
1331   (loop-disallow-conditional :with)
1332   (do ((var) (val) (dtype)) (nil)
1333     (setq var (loop-pop-source)
1334           dtype (loop-optional-type var)
1335           val (cond ((loop-tequal (car *loop-source-code*) :=)
1336                      (loop-pop-source)
1337                      (loop-get-form))
1338                     (t nil)))
1339     (loop-make-variable var val dtype)
1340     (if (loop-tequal (car *loop-source-code*) :and)
1341         (loop-pop-source)
1342         (return (loop-bind-block)))))
1343 \f
1344 ;;;; the iteration driver
1345
1346 (defun loop-hack-iteration (entry)
1347   (flet ((make-endtest (list-of-forms)
1348            (cond ((null list-of-forms) nil)
1349                  ((member t list-of-forms) '(go end-loop))
1350                  (t `(when ,(if (null (cdr (setq list-of-forms
1351                                                  (nreverse list-of-forms))))
1352                                 (car list-of-forms)
1353                                 (cons 'or list-of-forms))
1354                        (go end-loop))))))
1355     (do ((pre-step-tests nil)
1356          (steps nil)
1357          (post-step-tests nil)
1358          (pseudo-steps nil)
1359          (pre-loop-pre-step-tests nil)
1360          (pre-loop-steps nil)
1361          (pre-loop-post-step-tests nil)
1362          (pre-loop-pseudo-steps nil)
1363          (tem) (data))
1364         (nil)
1365       ;; Note that we collect endtests in reverse order, but steps in correct
1366       ;; order. MAKE-ENDTEST does the nreverse for us.
1367       (setq tem (setq data
1368                       (apply (symbol-function (first entry)) (rest entry))))
1369       (and (car tem) (push (car tem) pre-step-tests))
1370       (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1371       (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1372       (setq pseudo-steps
1373             (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1374       (setq tem (cdr tem))
1375       (when *loop-emitted-body*
1376         (loop-error "iteration in LOOP follows body code"))
1377       (unless tem (setq tem data))
1378       (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1379       ;; FIXME: This (SETF FOO (NCONC FOO BAR)) idiom appears often enough
1380       ;; that it might be worth making it into an NCONCF macro.
1381       (setq pre-loop-steps
1382             (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1383       (when (car (setq tem (cdr tem)))
1384         (push (car tem) pre-loop-post-step-tests))
1385       (setq pre-loop-pseudo-steps
1386             (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1387       (unless (loop-tequal (car *loop-source-code*) :and)
1388         (setq *loop-before-loop*
1389               (list* (loop-make-desetq pre-loop-pseudo-steps)
1390                      (make-endtest pre-loop-post-step-tests)
1391                      (loop-make-psetq pre-loop-steps)
1392                      (make-endtest pre-loop-pre-step-tests)
1393                      *loop-before-loop*))
1394         (setq *loop-after-body*
1395               (list* (loop-make-desetq pseudo-steps)
1396                      (make-endtest post-step-tests)
1397                      (loop-make-psetq steps)
1398                      (make-endtest pre-step-tests)
1399                      *loop-after-body*))
1400         (loop-bind-block)
1401         (return nil))
1402       (loop-pop-source)                         ; Flush the "AND".
1403       (when (and (not (loop-universe-implicit-for-required *loop-universe*))
1404                  (setq tem
1405                        (loop-lookup-keyword
1406                         (car *loop-source-code*)
1407                         (loop-universe-iteration-keywords *loop-universe*))))
1408         ;; The latest ANSI clarification is that the FOR/AS after the AND must
1409         ;; NOT be supplied.
1410         (loop-pop-source)
1411         (setq entry tem)))))
1412 \f
1413 ;;;; main iteration drivers
1414
1415 ;;; FOR variable keyword ..args..
1416 (defun loop-do-for ()
1417   (let* ((var (loop-pop-source))
1418          (data-type (loop-optional-type var))
1419          (keyword (loop-pop-source))
1420          (first-arg nil)
1421          (tem nil))
1422     (setq first-arg (loop-get-form))
1423     (unless (and (symbolp keyword)
1424                  (setq tem (loop-lookup-keyword
1425                              keyword
1426                              (loop-universe-for-keywords *loop-universe*))))
1427       (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP."
1428                   keyword))
1429     (apply (car tem) var first-arg data-type (cdr tem))))
1430
1431 (defun loop-do-repeat ()
1432   (let ((form (loop-get-form))
1433         (type (loop-check-data-type (loop-optional-type)
1434                                     *loop-real-data-type*)))
1435     (when (and (consp form) (eq (car form) 'the) (subtypep (second form) type))
1436       (setq type (second form)))
1437     (multiple-value-bind (number constantp value)
1438         (loop-constant-fold-if-possible form type)
1439       (cond ((and constantp (<= value 1)) `(t () () () ,(<= value 0) () () ()))
1440             (t (let ((var (loop-make-variable (loop-gentemp 'loop-repeat-)
1441                                               number
1442                                               type)))
1443                  (if constantp
1444                      `((not (plusp (setq ,var (1- ,var))))
1445                        () () () () () () ())
1446                      `((minusp (setq ,var (1- ,var)))
1447                        () () ()))))))))
1448
1449 (defun loop-when-it-variable ()
1450   (or *loop-when-it-variable*
1451       (setq *loop-when-it-variable*
1452             (loop-make-variable (loop-gentemp 'loop-it-) nil nil))))
1453 \f
1454 ;;;; various FOR/AS subdispatches
1455
1456 ;;; ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when the THEN
1457 ;;; is omitted (other than being more stringent in its placement), and like the
1458 ;;; old "FOR x FIRST y THEN z" when the THEN is present. I.e., the first
1459 ;;; initialization occurs in the loop body (first-step), not in the variable
1460 ;;; binding phase.
1461 (defun loop-ansi-for-equals (var val data-type)
1462   (loop-make-iteration-variable var nil data-type)
1463   (cond ((loop-tequal (car *loop-source-code*) :then)
1464          ;; Then we are the same as "FOR x FIRST y THEN z".
1465          (loop-pop-source)
1466          `(() (,var ,(loop-get-form)) () ()
1467            () (,var ,val) () ()))
1468         (t ;; We are the same as "FOR x = y".
1469          `(() (,var ,val) () ()))))
1470
1471 (defun loop-for-across (var val data-type)
1472   (loop-make-iteration-variable var nil data-type)
1473   (let ((vector-var (loop-gentemp 'loop-across-vector-))
1474         (index-var (loop-gentemp 'loop-across-index-)))
1475     (multiple-value-bind (vector-form constantp vector-value)
1476         (loop-constant-fold-if-possible val 'vector)
1477       (loop-make-variable
1478         vector-var vector-form
1479         (if (and (consp vector-form) (eq (car vector-form) 'the))
1480             (cadr vector-form)
1481             'vector))
1482       (loop-make-variable index-var 0 'fixnum)
1483       (let* ((length 0)
1484              (length-form (cond ((not constantp)
1485                                  (let ((v (loop-gentemp 'loop-across-limit-)))
1486                                    (push `(setq ,v (length ,vector-var))
1487                                          *loop-prologue*)
1488                                    (loop-make-variable v 0 'fixnum)))
1489                                 (t (setq length (length vector-value)))))
1490              (first-test `(>= ,index-var ,length-form))
1491              (other-test first-test)
1492              (step `(,var (aref ,vector-var ,index-var)))
1493              (pstep `(,index-var (1+ ,index-var))))
1494         (declare (fixnum length))
1495         (when constantp
1496           (setq first-test (= length 0))
1497           (when (<= length 1)
1498             (setq other-test t)))
1499         `(,other-test ,step () ,pstep
1500           ,@(and (not (eq first-test other-test))
1501                  `(,first-test ,step () ,pstep)))))))
1502 \f
1503 ;;;; list iteration
1504
1505 (defun loop-list-step (listvar)
1506   ;; We are not equipped to analyze whether 'FOO is the same as #'FOO here in
1507   ;; any sensible fashion, so let's give an obnoxious warning whenever 'FOO is
1508   ;; used as the stepping function.
1509   ;;
1510   ;; While a Discerning Compiler may deal intelligently with
1511   ;; (FUNCALL 'FOO ...), not recognizing FOO may defeat some LOOP
1512   ;; optimizations.
1513   (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1514                         (loop-pop-source)
1515                         (loop-get-form))
1516                        (t '(function cdr)))))
1517     (cond ((and (consp stepper) (eq (car stepper) 'quote))
1518            (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1519            `(funcall ,stepper ,listvar))
1520           ((and (consp stepper) (eq (car stepper) 'function))
1521            (list (cadr stepper) listvar))
1522           (t
1523            `(funcall ,(loop-make-variable (loop-gentemp 'loop-fn-)
1524                                           stepper
1525                                           'function)
1526                      ,listvar)))))
1527
1528 (defun loop-for-on (var val data-type)
1529   (multiple-value-bind (list constantp list-value)
1530       (loop-constant-fold-if-possible val)
1531     (let ((listvar var))
1532       (cond ((and var (symbolp var))
1533              (loop-make-iteration-variable var list data-type))
1534             (t (loop-make-variable (setq listvar (loop-gentemp)) list 'list)
1535                (loop-make-iteration-variable var nil data-type)))
1536       (let ((list-step (loop-list-step listvar)))
1537         (let* ((first-endtest
1538                 (hide-variable-reference
1539                  (eq var listvar)
1540                  listvar
1541                  ;; the following should use `atom' instead of `endp', per
1542                  ;; [bug2428]
1543                  `(atom ,listvar)))
1544                (other-endtest first-endtest))
1545           (when (and constantp (listp list-value))
1546             (setq first-endtest (null list-value)))
1547           (cond ((eq var listvar)
1548                  ;; Contour of the loop is different because we use the user's
1549                  ;; variable...
1550                  `(() (,listvar ,(hide-variable-reference t listvar list-step))
1551                    ,other-endtest () () () ,first-endtest ()))
1552                 (t (let ((step `(,var ,listvar))
1553                          (pseudo `(,listvar ,list-step)))
1554                      `(,other-endtest ,step () ,pseudo
1555                        ,@(and (not (eq first-endtest other-endtest))
1556                               `(,first-endtest ,step () ,pseudo)))))))))))
1557
1558 (defun loop-for-in (var val data-type)
1559   (multiple-value-bind (list constantp list-value)
1560       (loop-constant-fold-if-possible val)
1561     (let ((listvar (loop-gentemp 'loop-list-)))
1562       (loop-make-iteration-variable var nil data-type)
1563       (loop-make-variable listvar list 'list)
1564       (let ((list-step (loop-list-step listvar)))
1565         (let* ((first-endtest `(endp ,listvar))
1566                (other-endtest first-endtest)
1567                (step `(,var (car ,listvar)))
1568                (pseudo-step `(,listvar ,list-step)))
1569           (when (and constantp (listp list-value))
1570             (setq first-endtest (null list-value)))
1571           `(,other-endtest ,step () ,pseudo-step
1572             ,@(and (not (eq first-endtest other-endtest))
1573                    `(,first-endtest ,step () ,pseudo-step))))))))
1574 \f
1575 ;;;; iteration paths
1576
1577 (defstruct (loop-path
1578             (:copier nil)
1579             (:predicate nil))
1580   names
1581   preposition-groups
1582   inclusive-permitted
1583   function
1584   user-data)
1585
1586 (defun add-loop-path (names function universe
1587                       &key preposition-groups inclusive-permitted user-data)
1588   (declare (type loop-universe universe))
1589   (unless (listp names)
1590     (setq names (list names)))
1591   (let ((ht (loop-universe-path-keywords universe))
1592         (lp (make-loop-path
1593               :names (mapcar #'symbol-name names)
1594               :function function
1595               :user-data user-data
1596               :preposition-groups (mapcar (lambda (x)
1597                                             (if (listp x) x (list x)))
1598                                           preposition-groups)
1599               :inclusive-permitted inclusive-permitted)))
1600     (dolist (name names)
1601       (setf (gethash (symbol-name name) ht) lp))
1602     lp))
1603 \f
1604 ;;; Note:  path functions are allowed to use loop-make-variable, hack
1605 ;;; the prologue, etc.
1606 (defun loop-for-being (var val data-type)
1607   ;; FOR var BEING each/the pathname prep-phrases using-stuff... each/the =
1608   ;; EACH or THE. Not clear if it is optional, so I guess we'll warn.
1609   (let ((path nil)
1610         (data nil)
1611         (inclusive nil)
1612         (stuff nil)
1613         (initial-prepositions nil))
1614     (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1615           ((loop-tequal (car *loop-source-code*) :and)
1616            (loop-pop-source)
1617            (setq inclusive t)
1618            (unless (loop-tmember (car *loop-source-code*)
1619                                  '(:its :each :his :her))
1620              (loop-error "~S was found where ITS or EACH expected in LOOP iteration path syntax."
1621                          (car *loop-source-code*)))
1622            (loop-pop-source)
1623            (setq path (loop-pop-source))
1624            (setq initial-prepositions `((:in ,val))))
1625           (t (loop-error "unrecognizable LOOP iteration path syntax: missing EACH or THE?")))
1626     (cond ((not (symbolp path))
1627            (loop-error
1628             "~S was found where a LOOP iteration path name was expected."
1629             path))
1630           ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1631            (loop-error "~S is not the name of a LOOP iteration path." path))
1632           ((and inclusive (not (loop-path-inclusive-permitted data)))
1633            (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1634     (let ((fun (loop-path-function data))
1635           (preps (nconc initial-prepositions
1636                         (loop-collect-prepositional-phrases
1637                          (loop-path-preposition-groups data)
1638                          t)))
1639           (user-data (loop-path-user-data data)))
1640       (when (symbolp fun) (setq fun (symbol-function fun)))
1641       (setq stuff (if inclusive
1642                       (apply fun var data-type preps :inclusive t user-data)
1643                       (apply fun var data-type preps user-data))))
1644     (when *loop-named-variables*
1645       (loop-error "Unused USING variables: ~S." *loop-named-variables*))
1646     ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back). Protect the
1647     ;; system from the user and the user from himself.
1648     (unless (member (length stuff) '(6 10))
1649       (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1650                   path))
1651     (do ((l (car stuff) (cdr l)) (x)) ((null l))
1652       (if (atom (setq x (car l)))
1653           (loop-make-iteration-variable x nil nil)
1654           (loop-make-iteration-variable (car x) (cadr x) (caddr x))))
1655     (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1656     (cddr stuff)))
1657 \f
1658 (defun named-variable (name)
1659   (let ((tem (loop-tassoc name *loop-named-variables*)))
1660     (declare (list tem))
1661     (cond ((null tem) (values (loop-gentemp) nil))
1662           (t (setq *loop-named-variables* (delete tem *loop-named-variables*))
1663              (values (cdr tem) t)))))
1664
1665 (defun loop-collect-prepositional-phrases (preposition-groups
1666                                            &optional
1667                                            USING-allowed
1668                                            initial-phrases)
1669   (flet ((in-group-p (x group) (car (loop-tmember x group))))
1670     (do ((token nil)
1671          (prepositional-phrases initial-phrases)
1672          (this-group nil nil)
1673          (this-prep nil nil)
1674          (disallowed-prepositions
1675            (mapcan #'(lambda (x)
1676                        (copy-list
1677                          (find (car x) preposition-groups :test #'in-group-p)))
1678                    initial-phrases))
1679          (used-prepositions (mapcar #'car initial-phrases)))
1680         ((null *loop-source-code*) (nreverse prepositional-phrases))
1681       (declare (symbol this-prep))
1682       (setq token (car *loop-source-code*))
1683       (dolist (group preposition-groups)
1684         (when (setq this-prep (in-group-p token group))
1685           (return (setq this-group group))))
1686       (cond (this-group
1687              (when (member this-prep disallowed-prepositions)
1688                (loop-error
1689                  (if (member this-prep used-prepositions)
1690                      "A ~S prepositional phrase occurs multiply for some LOOP clause."
1691                      "Preposition ~S was used when some other preposition has subsumed it.")
1692                  token))
1693              (setq used-prepositions (if (listp this-group)
1694                                          (append this-group used-prepositions)
1695                                          (cons this-group used-prepositions)))
1696              (loop-pop-source)
1697              (push (list this-prep (loop-get-form)) prepositional-phrases))
1698             ((and USING-allowed (loop-tequal token 'using))
1699              (loop-pop-source)
1700              (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1701                (when (or (atom z)
1702                          (atom (cdr z))
1703                          (not (null (cddr z)))
1704                          (not (symbolp (car z)))
1705                          (and (cadr z) (not (symbolp (cadr z)))))
1706                  (loop-error "~S bad variable pair in path USING phrase" z))
1707                (when (cadr z)
1708                  (if (setq tem (loop-tassoc (car z) *loop-named-variables*))
1709                      (loop-error
1710                        "The variable substitution for ~S occurs twice in a USING phrase,~@
1711                         with ~S and ~S."
1712                        (car z) (cadr z) (cadr tem))
1713                      (push (cons (car z) (cadr z)) *loop-named-variables*)))
1714                (when (or (null *loop-source-code*)
1715                          (symbolp (car *loop-source-code*)))
1716                  (return nil))))
1717             (t (return (nreverse prepositional-phrases)))))))
1718 \f
1719 ;;;; master sequencer function
1720
1721 (defun loop-sequencer (indexv indexv-type indexv-user-specified-p
1722                           variable variable-type
1723                           sequence-variable sequence-type
1724                           step-hack default-top
1725                           prep-phrases)
1726    (let ((endform nil) ; Form (constant or variable) with limit value
1727          (sequencep nil) ; T if sequence arg has been provided
1728          (testfn nil) ; endtest function
1729          (test nil) ; endtest form
1730          (stepby (1+ (or (loop-typed-init indexv-type) 0))) ; our increment
1731          (stepby-constantp t)
1732          (step nil) ; step form
1733          (dir nil) ; direction of stepping: NIL, :UP, :DOWN
1734          (inclusive-iteration nil) ; T if include last index
1735          (start-given nil) ; T when prep phrase has specified start
1736          (start-value nil)
1737          (start-constantp nil)
1738          (limit-given nil) ; T when prep phrase has specified end
1739          (limit-constantp nil)
1740          (limit-value nil)
1741          )
1742      (when variable (loop-make-iteration-variable variable nil variable-type))
1743      (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1744        (setq prep (caar l) form (cadar l))
1745        (case prep
1746          ((:of :in)
1747           (setq sequencep t)
1748           (loop-make-variable sequence-variable form sequence-type))
1749          ((:from :downfrom :upfrom)
1750           (setq start-given t)
1751           (cond ((eq prep :downfrom) (setq dir ':down))
1752                 ((eq prep :upfrom) (setq dir ':up)))
1753           (multiple-value-setq (form start-constantp start-value)
1754             (loop-constant-fold-if-possible form indexv-type))
1755           (loop-make-iteration-variable indexv form indexv-type))
1756          ((:upto :to :downto :above :below)
1757           (cond ((loop-tequal prep :upto) (setq inclusive-iteration
1758                                                 (setq dir ':up)))
1759                 ((loop-tequal prep :to) (setq inclusive-iteration t))
1760                 ((loop-tequal prep :downto) (setq inclusive-iteration
1761                                                   (setq dir ':down)))
1762                 ((loop-tequal prep :above) (setq dir ':down))
1763                 ((loop-tequal prep :below) (setq dir ':up)))
1764           (setq limit-given t)
1765           (multiple-value-setq (form limit-constantp limit-value)
1766             (loop-constant-fold-if-possible form indexv-type))
1767           (setq endform (if limit-constantp
1768                             `',limit-value
1769                             (loop-make-variable
1770                               (loop-gentemp 'loop-limit-) form indexv-type))))
1771          (:by
1772            (multiple-value-setq (form stepby-constantp stepby)
1773              (loop-constant-fold-if-possible form indexv-type))
1774            (unless stepby-constantp
1775              (loop-make-variable (setq stepby (loop-gentemp 'loop-step-by-))
1776                                  form
1777                                  indexv-type)))
1778          (t (loop-error
1779               "~S invalid preposition in sequencing or sequence path;~@
1780                maybe invalid prepositions were specified in iteration path descriptor?"
1781               prep)))
1782        (when (and odir dir (not (eq dir odir)))
1783          (loop-error "conflicting stepping directions in LOOP sequencing path"))
1784        (setq odir dir))
1785      (when (and sequence-variable (not sequencep))
1786        (loop-error "missing OF or IN phrase in sequence path"))
1787      ;; Now fill in the defaults.
1788      (unless start-given
1789        (loop-make-iteration-variable
1790          indexv
1791          (setq start-constantp t
1792                start-value (or (loop-typed-init indexv-type) 0))
1793          indexv-type))
1794      (cond ((member dir '(nil :up))
1795             (when (or limit-given default-top)
1796               (unless limit-given
1797                 (loop-make-variable (setq endform
1798                                           (loop-gentemp 'loop-seq-limit-))
1799                                     nil indexv-type)
1800                 (push `(setq ,endform ,default-top) *loop-prologue*))
1801               (setq testfn (if inclusive-iteration '> '>=)))
1802             (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1803            (t (unless start-given
1804                 (unless default-top
1805                   (loop-error "don't know where to start stepping"))
1806                 (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1807               (when (and default-top (not endform))
1808                 (setq endform (loop-typed-init indexv-type)
1809                       inclusive-iteration t))
1810               (when endform (setq testfn (if inclusive-iteration  '< '<=)))
1811               (setq step
1812                     (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1813      (when testfn
1814        (setq test
1815              (hide-variable-reference t indexv `(,testfn ,indexv ,endform))))
1816      (when step-hack
1817        (setq step-hack
1818              `(,variable ,(hide-variable-reference indexv-user-specified-p
1819                                                    indexv
1820                                                    step-hack))))
1821      (let ((first-test test) (remaining-tests test))
1822        (when (and stepby-constantp start-constantp limit-constantp)
1823          (when (setq first-test
1824                      (funcall (symbol-function testfn)
1825                               start-value
1826                               limit-value))
1827            (setq remaining-tests t)))
1828        `(() (,indexv ,(hide-variable-reference t indexv step))
1829          ,remaining-tests ,step-hack () () ,first-test ,step-hack))))
1830 \f
1831 ;;;; interfaces to the master sequencer
1832
1833 (defun loop-for-arithmetic (var val data-type kwd)
1834   (loop-sequencer
1835     var (loop-check-data-type data-type *loop-real-data-type*) t
1836     nil nil nil nil nil nil
1837     (loop-collect-prepositional-phrases
1838       '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1839       nil (list (list kwd val)))))
1840
1841 (defun loop-sequence-elements-path (variable data-type prep-phrases
1842                                     &key
1843                                     fetch-function
1844                                     size-function
1845                                     sequence-type
1846                                     element-type)
1847   (multiple-value-bind (indexv indexv-user-specified-p) (named-variable 'index)
1848     (let ((sequencev (named-variable 'sequence)))
1849       (list* nil nil                            ; dummy bindings and prologue
1850              (loop-sequencer
1851                indexv 'fixnum indexv-user-specified-p
1852                variable (or data-type element-type)
1853                sequencev sequence-type
1854                `(,fetch-function ,sequencev ,indexv)
1855                `(,size-function ,sequencev)
1856                prep-phrases)))))
1857 \f
1858 ;;;; builtin LOOP iteration paths
1859
1860 #||
1861 (loop for v being the hash-values of ht do (print v))
1862 (loop for k being the hash-keys of ht do (print k))
1863 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1864 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1865 ||#
1866
1867 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
1868                                        &key (which (required-argument)))
1869   (declare (type (member :hash-key :hash-value) which))
1870   (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1871          (loop-error "too many prepositions!"))
1872         ((null prep-phrases)
1873          (loop-error "missing OF or IN in ~S iteration path")))
1874   (let ((ht-var (loop-gentemp 'loop-hashtab-))
1875         (next-fn (loop-gentemp 'loop-hashtab-next-))
1876         (dummy-predicate-var nil)
1877         (post-steps nil))
1878     (multiple-value-bind (other-var other-p)
1879         (named-variable (if (eq which 'hash-key) 'hash-value 'hash-key))
1880       ;; @@@@ named-variable returns a second value of T if the name was
1881       ;; actually specified, so clever code can throw away the gensym'ed up
1882       ;; variable if it isn't really needed. The following is for those
1883       ;; implementations in which we cannot put dummy NILs into
1884       ;; multiple-value-setq variable lists.
1885       (setq other-p t
1886             dummy-predicate-var (loop-when-it-variable))
1887       (let ((key-var nil)
1888             (val-var nil)
1889             (bindings `((,variable nil ,data-type)
1890                         (,ht-var ,(cadar prep-phrases))
1891                         ,@(and other-p other-var `((,other-var nil))))))
1892         (if (eq which 'hash-key)
1893             (setq key-var variable val-var (and other-p other-var))
1894             (setq key-var (and other-p other-var) val-var variable))
1895         (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1896         (when (consp key-var)
1897           (setq post-steps
1898                 `(,key-var ,(setq key-var (loop-gentemp 'loop-hash-key-temp-))
1899                            ,@post-steps))
1900           (push `(,key-var nil) bindings))
1901         (when (consp val-var)
1902           (setq post-steps
1903                 `(,val-var ,(setq val-var (loop-gentemp 'loop-hash-val-temp-))
1904                            ,@post-steps))
1905           (push `(,val-var nil) bindings))
1906         `(,bindings                             ;bindings
1907           ()                                    ;prologue
1908           ()                                    ;pre-test
1909           ()                                    ;parallel steps
1910           (not (multiple-value-setq (,dummy-predicate-var ,key-var ,val-var)
1911                  (,next-fn)))   ;post-test
1912           ,post-steps)))))
1913
1914 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
1915                                             &key symbol-types)
1916   (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1917          (loop-error "Too many prepositions!"))
1918         ((null prep-phrases)
1919          (loop-error "missing OF or IN in ~S iteration path")))
1920   (unless (symbolp variable)
1921     (loop-error "Destructuring is not valid for package symbol iteration."))
1922   (let ((pkg-var (loop-gentemp 'loop-pkgsym-))
1923         (next-fn (loop-gentemp 'loop-pkgsym-next-)))
1924     (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types))
1925           *loop-wrappers*)
1926     `(((,variable nil ,data-type) (,pkg-var ,(cadar prep-phrases)))
1927       ()
1928       ()
1929       ()
1930       (not (multiple-value-setq (,(loop-when-it-variable)
1931                                  ,variable)
1932              (,next-fn)))
1933       ())))
1934 \f
1935 ;;;; ANSI LOOP
1936
1937 (defun make-ansi-loop-universe (extended-p)
1938   (let ((w (make-standard-loop-universe
1939              :keywords `((named (loop-do-named))
1940                          (initially (loop-do-initially))
1941                          (finally (loop-do-finally))
1942                          (do (loop-do-do))
1943                          (doing (loop-do-do))
1944                          (return (loop-do-return))
1945                          (collect (loop-list-collection list))
1946                          (collecting (loop-list-collection list))
1947                          (append (loop-list-collection append))
1948                          (appending (loop-list-collection append))
1949                          (nconc (loop-list-collection nconc))
1950                          (nconcing (loop-list-collection nconc))
1951                          (count (loop-sum-collection count
1952                                                      ,*loop-real-data-type*
1953                                                      fixnum))
1954                          (counting (loop-sum-collection count
1955                                                         ,*loop-real-data-type*
1956                                                         fixnum))
1957                          (sum (loop-sum-collection sum number number))
1958                          (summing (loop-sum-collection sum number number))
1959                          (maximize (loop-maxmin-collection max))
1960                          (minimize (loop-maxmin-collection min))
1961                          (maximizing (loop-maxmin-collection max))
1962                          (minimizing (loop-maxmin-collection min))
1963                          (always (loop-do-always t nil)) ; Normal, do always
1964                          (never (loop-do-always t t)) ; Negate test on always.
1965                          (thereis (loop-do-thereis t))
1966                          (while (loop-do-while nil :while)) ; Normal, do while
1967                          (until (loop-do-while t :until)) ;Negate test on while
1968                          (when (loop-do-if when nil))   ; Normal, do when
1969                          (if (loop-do-if if nil))       ; synonymous
1970                          (unless (loop-do-if unless t)) ; Negate test on when
1971                          (with (loop-do-with)))
1972              :for-keywords '((= (loop-ansi-for-equals))
1973                              (across (loop-for-across))
1974                              (in (loop-for-in))
1975                              (on (loop-for-on))
1976                              (from (loop-for-arithmetic :from))
1977                              (downfrom (loop-for-arithmetic :downfrom))
1978                              (upfrom (loop-for-arithmetic :upfrom))
1979                              (below (loop-for-arithmetic :below))
1980                              (to (loop-for-arithmetic :to))
1981                              (upto (loop-for-arithmetic :upto))
1982                              (being (loop-for-being)))
1983              :iteration-keywords '((for (loop-do-for))
1984                                    (as (loop-do-for))
1985                                    (repeat (loop-do-repeat)))
1986              :type-symbols '(array atom bignum bit bit-vector character
1987                              compiled-function complex cons double-float
1988                              fixnum float function hash-table integer
1989                              keyword list long-float nil null number
1990                              package pathname random-state ratio rational
1991                              readtable sequence short-float simple-array
1992                              simple-bit-vector simple-string simple-vector
1993                              single-float standard-char stream string
1994                              base-char symbol t vector)
1995              :type-keywords nil
1996              :ansi (if extended-p :extended t))))
1997     (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
1998                    :preposition-groups '((:of :in))
1999                    :inclusive-permitted nil
2000                    :user-data '(:which :hash-key))
2001     (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
2002                    :preposition-groups '((:of :in))
2003                    :inclusive-permitted nil
2004                    :user-data '(:which :hash-value))
2005     (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
2006                    :preposition-groups '((:of :in))
2007                    :inclusive-permitted nil
2008                    :user-data '(:symbol-types (:internal
2009                                                :external
2010                                                :inherited)))
2011     (add-loop-path '(external-symbol external-symbols)
2012                    'loop-package-symbols-iteration-path w
2013                    :preposition-groups '((:of :in))
2014                    :inclusive-permitted nil
2015                    :user-data '(:symbol-types (:external)))
2016     (add-loop-path '(present-symbol present-symbols)
2017                    'loop-package-symbols-iteration-path w
2018                    :preposition-groups '((:of :in))
2019                    :inclusive-permitted nil
2020                    :user-data '(:symbol-types (:internal)))
2021     w))
2022
2023 (defparameter *loop-ansi-universe*
2024   (make-ansi-loop-universe nil))
2025
2026 (defun loop-standard-expansion (keywords-and-forms environment universe)
2027   (if (and keywords-and-forms (symbolp (car keywords-and-forms)))
2028     (loop-translate keywords-and-forms environment universe)
2029     (let ((tag (gensym)))
2030       `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
2031
2032 (sb!int:defmacro-mundanely loop (&environment env &rest keywords-and-forms)
2033   (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))
2034
2035 (sb!int:defmacro-mundanely loop-finish ()
2036   #!+sb-doc
2037   "Cause the iteration to terminate \"normally\", the same as implicit
2038 termination by an iteration driving clause, or by use of WHILE or
2039 UNTIL -- the epilogue code (if any) will be run, and any implicitly
2040 collected result will be returned as the value of the LOOP."
2041   '(go end-loop))