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

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

Work in progress.

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