source: trunk/j/src/org/armedbear/lisp/loop.lisp @ 9022

Last change on this file since 9022 was 9022, checked in by piso, 16 years ago

LOOP-SEQUENCER: #-sbcl (declare (ignore %decl))

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