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

Last change on this file since 3996 was 3996, checked in by piso, 18 years ago

Moved (PROVIDE :LOOP) to the end of the file.

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