1 ;;; -*- Mode: LISP; Syntax: Common-lisp; Base: 10; Lowercase:T -*-
3 ;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
4 ;;;> All Rights Reserved.
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.
18 ;;;> Massachusetts Institute of Technology
19 ;;;> 77 Massachusetts Avenue
20 ;;;> Cambridge, Massachusetts 02139
21 ;;;> United States of America
24 ;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
25 ;;;> All Rights Reserved.
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.
39 ;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
40 ;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
43 ;;;> 8 New England Executive Park, East
44 ;;;> Burlington, Massachusetts 01803
45 ;;;> United States of America
48 ;;;; LOOP Iteration Macro
53 ;;; - Because much of this file is wrapped in eval-when (:compile-toplevel),
54 ;;; (i.e. the host-side macroexpanders), it's probably best to
55 ;;; recompile/reload this complete file rather than on a per-toplevel
64 ;;;(in-package :ansi-loop)
67 (provide :muerte
/loop
:load-priority
0)
70 ;;;This is the "current" loop context in use when we are expanding a
71 ;;;loop. It gets bound on each invocation of LOOP.
74 (defmacro loop-copylist
* (l)
75 #+Genera
`(lisp:copy-list
,l nil t
) ; arglist = (list &optional area force-dotted)
77 #-Genera
`(copy-list ,l
))
79 (eval-when (:compile-toplevel
)
80 (defvar *loop-real-data-type
* 'real
)
81 (defvar *loop-universe
*)
83 #+Cloe-Runtime
;Don't ask.
84 (car (push "%Z% %M% %I% %E% %U%" system
::*module-identifications
*))
89 ;;; The LOOP iteration macro is one of a number of pieces of code
90 ;;; originally developed at MIT for which free distribution has been
91 ;;; permitted, as long as the code is not sold for profit, and as long
92 ;;; as notification of MIT's interest in the code is preserved.
94 ;;; This version of LOOP, which is almost entirely rewritten both as
95 ;;; clean-up and to conform with the ANSI Lisp LOOP standard, started
96 ;;; life as MIT LOOP version 829 (which was a part of NIL, possibly
99 ;;; A "light revision" was performed by me (Glenn Burke) while at
100 ;;; Palladian Software in April 1986, to make the code run in Common
101 ;;; Lisp. This revision was informally distributed to a number of
102 ;;; people, and was sort of the "MIT" version of LOOP for running in
105 ;;; A later more drastic revision was performed at Palladian perhaps a
106 ;;; year later. This version was more thoroughly Common Lisp in style,
107 ;;; with a few miscellaneous internal improvements and extensions. I
108 ;;; have lost track of this source, apparently never having moved it to
109 ;;; the MIT distribution point. I do not remember if it was ever
112 ;;; This revision for the ANSI standard is based on the code of my April
113 ;;; 1986 version, with almost everything redesigned and/or rewritten.
116 ;;; The design of this LOOP is intended to permit, using mostly the same
117 ;;; kernel of code, up to three different "loop" macros:
119 ;;; (1) The unextended, unextensible ANSI standard LOOP;
121 ;;; (2) A clean "superset" extension of the ANSI LOOP which provides
122 ;;; functionality similar to that of the old LOOP, but "in the style of"
123 ;;; the ANSI LOOP. For instance, user-definable iteration paths, with a
124 ;;; somewhat cleaned-up interface.
126 ;;; (3) Extensions provided in another file which can make this LOOP
127 ;;; kernel behave largely compatibly with the Genera-vintage LOOP macro,
128 ;;; with only a small addition of code (instead of two whole, separate,
131 ;;; Each of the above three LOOP variations can coexist in the same LISP
136 ;;;; Miscellaneous Environment Things
140 ;;;@@@@The LOOP-Prefer-POP feature makes LOOP generate code which "prefers" to use POP or
141 ;;; its obvious expansion (prog1 (car x) (setq x (cdr x))). Usually this involves
142 ;;; shifting fenceposts in an iteration or series of carcdr operations. This is
143 ;;; primarily recognized in the list iterators (FOR .. {IN,ON}), and LOOP's
144 ;;; destructuring setq code.
145 ;;;(eval-when (compile load eval)
146 ;;; #+(or Genera Minima) (pushnew :LOOP-Prefer-POP *features*)
150 ;;; The uses of this macro are retained in the CL version of loop, in
151 ;;; case they are needed in a particular implementation. Originally
152 ;;; dating from the use of the Zetalisp COPYLIST* function, this is used
153 ;;; in situations where, were cdr-coding in use, having cdr-NIL at the
154 ;;; end of the list might be suboptimal because the end of the list will
155 ;;; probably be RPLACDed and so cdr-normal should be used instead.
156 (defmacro loop-copylist
* (l)
157 #+Genera
`(lisp:copy-list
,l nil t
) ; arglist = (list &optional area force-dotted)
159 #-Genera
`(copy-list ,l
)
163 (defvar *loop-gentemp
*
166 (defun loop-gentemp (&optional
(pref 'loopvar-
))
167 (gensym (string pref
))
170 (gentemp (string pref
))
171 (gensym (string pref
))))
176 (defun loop-optimization-quantities (env)
177 ;;@@@@ The ANSI conditionalization here is for those lisps that implement
178 ;; DECLARATION-INFORMATION (from cleanup SYNTACTIC-ENVIRONMENT-ACCESS).
179 ;; It is really commentary on how this code could be written. I don't
180 ;; actually expect there to be an ANSI #+-conditional -- it should be
181 ;; replaced with the appropriate conditional name for your
182 ;; implementation/dialect.
183 (declare #-ANSI
(ignore env
)
184 #+Genera
(values speed space safety compilation-speed debug
))
185 #+ANSI
(let ((stuff (declaration-information 'optimize env
)))
186 (values (or (cdr (assoc 'speed stuff
)) 1)
187 (or (cdr (assoc 'space stuff
)) 1)
188 (or (cdr (assoc 'safety stuff
)) 1)
189 (or (cdr (assoc 'compilation-speed stuff
)) 1)
190 (or (cdr (assoc 'debug stuff
)) 1)))
191 #+CLOE-Runtime
(values compiler
::time compiler
::space
192 compiler
::safety compiler
::compilation-speed
1)
193 #-
(or ANSI CLOE-Runtime
) (values 1 1 1 1 1))
196 ;;;@@@@ The following form takes a list of variables and a form which presumably
197 ;;; references those variables, and wraps it somehow so that the compiler does not
198 ;;; consider those variables have been referenced. The intent of this is that
199 ;;; iteration variables can be flagged as unused by the compiler, e.g. I in
200 ;;; (loop for i from 1 to 10 do (print t)), since we will tell it when a usage
201 ;;; of it is "invisible" or "not to be considered".
202 ;;;We implicitly assume that a setq does not count as a reference. That is, the
203 ;;; kind of form generated for the above loop construct to step I, simplified, is
204 ;;; `(SETQ I ,(HIDE-VARIABLE-REFERENCES '(I) '(1+ I))).
205 (defun hide-variable-references (variable-list form
)
206 (declare #-Genera
(ignore variable-list
))
207 #+Genera
(if variable-list
`(compiler:invisible-references
,variable-list
,form
) form
)
211 ;;;@@@@ The following function takes a flag, a variable, and a form which presumably
212 ;;; references that variable, and wraps it somehow so that the compiler does not
213 ;;; consider that variable to have been referenced. The intent of this is that
214 ;;; iteration variables can be flagged as unused by the compiler, e.g. I in
215 ;;; (loop for i from 1 to 10 do (print t)), since we will tell it when a usage
216 ;;; of it is "invisible" or "not to be considered".
217 ;;;We implicitly assume that a setq does not count as a reference. That is, the
218 ;;; kind of form generated for the above loop construct to step I, simplified, is
219 ;;; `(SETQ I ,(HIDE-VARIABLE-REFERENCES T 'I '(1+ I))).
220 ;;;Certain cases require that the "invisibility" of the reference be conditional upon
221 ;;; something. This occurs in cases of "named" variables (the USING clause). For instance,
222 ;;; we want IDX in (LOOP FOR E BEING THE VECTOR-ELEMENTS OF V USING (INDEX IDX) ...)
223 ;;; to be "invisible" when it is stepped, so that the user gets informed if IDX is
224 ;;; not referenced. However, if no USING clause is present, we definitely do not
225 ;;; want to be informed that some random gensym is not used.
226 ;;;It is easier for the caller to do this conditionally by passing a flag (which
227 ;;; happens to be the second value of NAMED-VARIABLE, q.v.) to this function than
228 ;;; for all callers to contain the conditional invisibility construction.
229 (defun hide-variable-reference (really-hide variable form
)
230 (declare #-Genera
(ignore really-hide variable
))
231 #+Genera
(if (and really-hide variable
(atom variable
)) ;Punt on destructuring patterns
232 `(compiler:invisible-references
(,variable
) ,form
)
237 ;;;; List Collection Macrology
240 (defmacro with-loop-list-collection-head
((head-var tail-var
&optional user-head-var
)
243 #+LISPM
(let ((head-place (or user-head-var head-var
)))
244 `(let* ((,head-place nil
)
246 ,(hide-variable-reference
247 user-head-var user-head-var
248 `(progn #+Genera
(scl:locf
,head-place
)
249 #-Genera
(system:variable-location
,head-place
)))))
251 #-LISPM
(let ((l (and user-head-var
(list (list user-head-var nil
)))))
252 #+CLOE
`(sys::with-stack-list
* (,head-var nil nil
)
253 (let ((,tail-var
,head-var
) ,@l
)
255 #-CLOE
`(let* ((,head-var
(list nil
)) (,tail-var
,head-var
) ,@l
)
259 (defmacro loop-collect-rplacd
(&environment env
260 (head-var tail-var
&optional user-head-var
) form
)
262 #+LISPM
(ignore head-var user-head-var
) ;use locatives, unconditionally update through the tail.
264 (setq form
(movitz::movitz-macroexpand form env
))
265 (flet ((cdr-wrap (form n
)
267 (do () ((<= n
4) (setq form
`(,(case n
273 (setq form
`(cddddr ,form
) n
(- n
4)))))
274 (let ((tail-form form
) (ncdrs nil
))
275 ;;Determine if the form being constructed is a list of known length.
277 (cond ((eq (car form
) 'list
)
278 (setq ncdrs
(1- (length (cdr form
))))
279 ;;@@@@ Because the last element is going to be RPLACDed,
280 ;; we don't want the cdr-coded implementations to use
281 ;; cdr-nil at the end (which would just force copying
282 ;; the whole list again).
283 #+LISPM
(setq tail-form
`(list* ,@(cdr form
) nil
)))
284 ((member (car form
) '(list* cons
))
285 (when (and (cddr form
) (member (car (last form
)) '(nil 'nil
)))
286 (setq ncdrs
(- (length (cdr form
)) 2))))))
289 `(when (setf (cdr ,tail-var
) ,tail-form
)
290 (setq ,tail-var
(last (cdr ,tail-var
)))))
291 ((< ncdrs
0) (return-from loop-collect-rplacd nil
))
293 ;;@@@@ Here we have a choice of two idioms:
294 ;; (rplacd tail (setq tail tail-form))
295 ;; (setq tail (setf (cdr tail) tail-form)).
296 ;;Genera and most others I have seen do better with the former.
297 `(rplacd ,tail-var
(setq ,tail-var
,tail-form
)))
298 (t `(setq ,tail-var
,(cdr-wrap `(setf (cdr ,tail-var
) ,tail-form
)
300 ;;If not using locatives or something similar to update the user's
301 ;; head variable, we've got to set it... It's harmless to repeatedly set it
302 ;; unconditionally, and probably faster than checking.
303 #-LISPM
(when user-head-var
304 (setq answer
`(progn ,answer
(setq ,user-head-var
(cdr ,head-var
)))))
308 (defmacro loop-collect-answer
(head-var &optional user-head-var
)
311 ;;If we use locatives to get tail-updating to update the head var,
312 ;; then the head var itself contains the answer. Otherwise we
315 #-LISPM
`(cdr ,head-var
))))
318 (defstruct (loop-minimax
319 (:constructor make-loop-minimax-internal
)
329 (defstruct (loop-universe
330 (:print-function print-loop-universe
)
333 keywords
;hash table, value = (fn-name . extra-data).
334 iteration-keywords
;hash table, value = (fn-name . extra-data).
335 for-keywords
;hash table, value = (fn-name . extra-data).
336 path-keywords
;hash table, value = (fn-name . extra-data).
337 type-symbols
;hash table of type SYMBOLS, test EQ, value = CL type specifier.
338 type-keywords
;hash table of type STRINGS, test EQUAL, value = CL type spec.
339 ansi
;NIL, T, or :EXTENDED.
340 implicit-for-required
;see loop-hack-iteration
344 (defstruct (loop-collector
352 (data nil
)) ;collector-specific data
354 (defstruct (loop-path
365 ;;;; Maximization Technology
367 (eval-when (:compile-toplevel
:execute
)
370 The basic idea of all this minimax randomness here is that we have to
371 have constructed all uses of maximize and minimize to a particular
372 "destination" before we can decide how to code them. The goal is to not
373 have to have any kinds of flags
, by knowing both that
(1) the type is
374 something which we can provide an initial minimum or maximum value for
375 and
(2) know that a MAXIMIZE and MINIMIZE are not being combined.
377 SO
, we have a datastructure which we annotate with all sorts of things
,
378 incrementally updating it as we generate loop body code
, and then use
379 a wrapper and internal macros to do the coding when the loop has been
384 (defvar *loop-minimax-type-infinities-alist
*
385 ;;@@@@ This is the sort of value this should take on for a Lisp that has
386 ;; "eminently usable" infinities. n.b. there are neither constants nor
387 ;; printed representations for infinities defined by CL.
388 ;;@@@@ This grotesque read-from-string below is to help implementations
389 ;; which croak on the infinity character when it appears in a token, even
390 ;; conditionalized out.
393 "((fixnum most-positive-fixnum most-negative-fixnum)
394 (short-float +1s\x0e -1s\x0e)
395 (single-float +1f\x0e -1f\x0e)
396 (double-float +1d\x0e -1d\x0e)
397 (long-float +1l\x0e -1l\x0e))")
398 ;;This is how the alist should look for a lisp that has no infinities. In
399 ;; that case, MOST-POSITIVE-x-FLOAT really IS the most positive.
400 #+(or CLOE-Runtime Minima
)
401 '((fixnum most-positive-fixnum most-negative-fixnum
)
402 (short-float most-positive-short-float most-negative-short-float
)
403 (single-float most-positive-single-float most-negative-single-float
)
404 (double-float most-positive-double-float most-negative-double-float
)
405 (long-float most-positive-long-float most-negative-long-float
))
406 ;; CMUCL has infinities so let's use them.
408 '((fixnum most-positive-fixnum most-negative-fixnum
)
409 (short-float ext
:single-float-positive-infinity ext
:single-float-negative-infinity
)
410 (single-float ext
:single-float-positive-infinity ext
:single-float-negative-infinity
)
411 (double-float ext
:double-float-positive-infinity ext
:double-float-negative-infinity
)
412 (long-float ext
:long-float-positive-infinity ext
:long-float-negative-infinity
))
413 ;; If we don't know, then we cannot provide "infinite" initial values for any of the
415 #-
(or Genera CLOE-Runtime Minima CMU
)
416 '((fixnum most-positive-fixnum most-negative-fixnum
))
419 (defun loop-gentemp (&optional
(pref 'loopvar-
))
420 (gensym (string pref
)))
422 (defun make-loop-minimax (answer-variable type
)
423 (let ((infinity-data (cdr (assoc type
*loop-minimax-type-infinities-alist
* :test
#'subtypep
))))
424 (make-loop-minimax-internal
425 :answer-variable answer-variable
427 :temp-variable
(loop-gentemp 'loop-maxmin-temp-
)
428 :flag-variable
(and (not infinity-data
) (loop-gentemp 'loop-maxmin-flag-
))
430 :infinity-data infinity-data
)))
433 (defun loop-note-minimax-operation (operation minimax
)
434 (pushnew (the symbol operation
) (loop-minimax-operations minimax
))
435 (when (and (cdr (loop-minimax-operations minimax
))
436 (not (loop-minimax-flag-variable minimax
)))
437 (setf (loop-minimax-flag-variable minimax
) (loop-gentemp 'loop-maxmin-flag-
)))
441 (defmacro with-minimax-value
(lm &body body
)
442 (let ((init (loop-typed-init (loop-minimax-type lm
)))
443 (which (car (loop-minimax-operations lm
)))
444 (infinity-data (loop-minimax-infinity-data lm
))
445 (answer-var (loop-minimax-answer-variable lm
))
446 (temp-var (loop-minimax-temp-variable lm
))
447 (flag-var (loop-minimax-flag-variable lm
))
448 (type (loop-minimax-type lm
)))
450 `(let ((,answer-var
,init
) (,temp-var
,init
) (,flag-var nil
))
451 (declare (type ,type
,answer-var
,temp-var
))
453 `(let ((,answer-var
,(if (eq which
'min
) (first infinity-data
) (second infinity-data
)))
455 (declare (type ,type
,answer-var
,temp-var
))
459 (defmacro loop-accumulate-minimax-value
(lm operation form
)
460 (let* ((answer-var (loop-minimax-answer-variable lm
))
461 (temp-var (loop-minimax-temp-variable lm
))
462 (flag-var (loop-minimax-flag-variable lm
))
464 (hide-variable-reference
465 t
(loop-minimax-answer-variable lm
)
469 ,temp-var
,answer-var
))))
471 (setq ,temp-var
,form
)
472 (when ,(if flag-var
`(or (not ,flag-var
) ,test
) test
)
473 (setq ,@(and flag-var
`(,flag-var t
))
474 ,answer-var
,temp-var
)))))
479 ;;;; Loop Keyword Tables
483 LOOP keyword tables are hash tables string keys and a test of EQUAL.
485 The actual descriptive
/dispatch structure used by LOOP is called a
"loop
486 universe" contains a few tables and parameterizations. The basic idea is
487 that we can provide a non-extensible ANSI-compatible loop environment
,
488 an extensible ANSI-superset loop environment
, and
(for such environments
489 as CLOE
) one which is
"sufficiently close" to the old Genera-vintage
490 LOOP for use by old user programs without requiring all of the old LOOP
497 (eval-when (:compile-toplevel
#+movitz-loop
:load-toplevel
)
500 ;;;Compare two "tokens". The first is the frob out of *LOOP-SOURCE-CODE*,
501 ;;; the second a symbol to check against.
502 (defun loop-tequal (x1 x2
)
503 (and (symbolp x1
) (string= x1 x2
)))
506 (defun loop-tassoc (kwd alist
)
507 (and (symbolp kwd
) (assoc kwd alist
:test
#'string
=)))
510 (defun loop-tmember (kwd list
)
511 (and (symbolp kwd
) (member kwd list
:test
#'string
=)))
514 (defun loop-lookup-keyword (loop-token table
)
515 (and (symbolp loop-token
)
516 (values (gethash (symbol-name loop-token
) table
))))
519 (defmacro loop-store-table-data
(symbol table datum
)
520 `(setf (gethash (symbol-name ,symbol
) ,table
) ,datum
))
525 (defun print-loop-universe (u stream level
)
526 (declare (ignore level
))
527 (let ((str (case (loop-universe-ansi u
)
530 (:extended
"Extended-ANSI")
531 (t (loop-universe-ansi u
)))))
532 ;;Cloe could be done with the above except for bootstrap lossage...
534 (format stream
"#<~S ~A ~X>" (type-of u
) str
(sys::address-of u
))
535 #+Genera
;@@@@ This is reallly the ANSI definition.
536 (print-unreadable-object (u stream
:type t
:identity t
)
539 (format stream
"#<~S ~A>" (type-of u
) str
)
544 (defun make-standard-loop-universe (&key keywords for-keywords iteration-keywords path-keywords
545 type-keywords type-symbols ansi
)
546 #-
(and CLOE Source-Bootstrap
) (check-type ansi
(member nil t
:extended
))
547 (flet ((maketable (entries)
548 (let* ((size (length entries
))
549 (ht (make-hash-table :size
(if (< size
10) 10 size
) :test
#'equal
)))
550 (dolist (x entries
) (setf (gethash (symbol-name (car x
)) ht
) (cadr x
)))
553 :keywords
(maketable keywords
)
554 :for-keywords
(maketable for-keywords
)
555 :iteration-keywords
(maketable iteration-keywords
)
556 :path-keywords
(maketable path-keywords
)
558 :implicit-for-required
(not (null ansi
))
559 :type-keywords
(maketable type-keywords
)
560 :type-symbols
(let* ((size (length type-symbols
))
561 (ht (make-hash-table :size
(if (< size
10) 10 size
) :test
#'eq
)))
562 (dolist (x type-symbols
)
563 (if (atom x
) (setf (gethash x ht
) x
) (setf (gethash (car x
) ht
) (cadr x
))))
570 (defvar *loop-destructuring-hooks
*
572 "If not NIL, this must be a list of two things:
573 a LET-like macro, and a SETQ-like macro, which perform LOOP-style destructuring.")
577 (defun loop-make-psetq (frobs)
581 (if (null (cddr frobs
)) (cadr frobs
)
582 `(prog1 ,(cadr frobs
)
583 ,(loop-make-psetq (cddr frobs
))))))))
586 (defun loop-make-desetq (var-val-pairs)
587 (if (null var-val-pairs
)
589 (cons (if *loop-destructuring-hooks
*
590 (cadr *loop-destructuring-hooks
*)
595 (defvar *loop-desetq-temporary
*
596 (make-symbol "LOOP-DESETQ-TEMP"))
599 ;;;; LOOP-local variables
601 ;;;This is the "current" pointer into the LOOP source code.
602 (defvar *loop-source-code
*)
605 ;;;This is the pointer to the original, for things like NAMED that
606 ;;;insist on being in a particular position
607 (defvar *loop-original-source-code
*)
610 ;;;This is *loop-source-code* as of the "last" clause. It is used
611 ;;;primarily for generating error messages (see loop-error, loop-warn).
612 (defvar *loop-source-context
*)
615 ;;;List of names for the LOOP, supplied by the NAMED clause.
616 (defvar *loop-names
*)
618 ;;;The macroexpansion environment given to the macro.
619 (defvar *loop-macro-environment
*)
621 ;;;This holds variable names specified with the USING clause.
622 ;;; See LOOP-NAMED-VARIABLE.
623 (defvar *loop-named-variables
*)
625 ;;; LETlist-like list being accumulated for one group of parallel bindings.
626 (defvar *loop-variables
*)
628 ;;;List of declarations being accumulated in parallel with
630 (defvar *loop-declarations
*)
632 ;;;Used by LOOP for destructuring binding, if it is doing that itself.
633 ;;; See loop-make-variable.
634 (defvar *loop-desetq-crocks
*)
636 ;;; List of wrapping forms, innermost first, which go immediately inside
637 ;;; the current set of parallel bindings being accumulated in
638 ;;; *loop-variables*. The wrappers are appended onto a body. E.g.,
639 ;;; this list could conceivably has as its value ((with-open-file (g0001
640 ;;; g0002 ...))), with g0002 being one of the bindings in
641 ;;; *loop-variables* (this is why the wrappers go inside of the variable
643 (defvar *loop-wrappers
*)
645 ;;;This accumulates lists of previous values of *loop-variables* and the
646 ;;;other lists above, for each new nesting of bindings. See
648 (defvar *loop-bind-stack
*)
650 ;;;This is a LOOP-global variable for the (obsolete) NODECLARE clause
651 ;;;which inhibits LOOP from actually outputting a type declaration for
652 ;;;an iteration (or any) variable.
653 (defvar *loop-nodeclare
*)
655 ;;;This is simply a list of LOOP iteration variables, used for checking
657 (defvar *loop-iteration-variables
*)
660 ;;;List of prologue forms of the loop, accumulated in reverse order.
661 (defvar *loop-prologue
*)
663 (defvar *loop-before-loop
*)
665 (defvar *loop-after-body
*)
667 ;;;This is T if we have emitted any body code, so that iteration driving
668 ;;;clauses can be disallowed. This is not strictly the same as
669 ;;;checking *loop-body*, because we permit some clauses such as RETURN
670 ;;;to not be considered "real" body (so as to permit the user to "code"
671 ;;;an abnormal return value "in loop").
672 (defvar *loop-emitted-body
*)
675 ;;;List of epilogue forms (supplied by FINALLY generally), accumulated
676 ;;; in reverse order.
677 (defvar *loop-epilogue
*)
679 ;;;List of epilogue forms which are supplied after the above "user"
680 ;;;epilogue. "normal" termination return values are provide by putting
681 ;;;the return form in here. Normally this is done using
682 ;;;loop-emit-final-value, q.v.
683 (defvar *loop-after-epilogue
*)
685 ;;;The "culprit" responsible for supplying a final value from the loop.
686 ;;;This is so loop-emit-final-value can moan about multiple return
687 ;;;values being supplied.
688 (defvar *loop-final-value-culprit
*)
690 ;;;If not NIL, we are in some branch of a conditional. Some clauses may
692 (defvar *loop-inside-conditional
*)
694 ;;;If not NIL, this is a temporary bound around the loop for holding the
695 ;;;temporary value for "it" in things like "when (f) collect it". It
696 ;;;may be used as a supertemporary by some other things.
697 (defvar *loop-when-it-variable
*)
699 ;;;Sometimes we decide we need to fold together parts of the loop, but
700 ;;;some part of the generated iteration code is different for the first
701 ;;;and remaining iterations. This variable will be the temporary which
702 ;;;is the flag used in the loop to tell whether we are in the first or
703 ;;;remaining iterations.
704 (defvar *loop-never-stepped-variable
*)
706 ;;;List of all the value-accumulation descriptor structures in the loop.
707 ;;; See loop-get-collection-info.
708 (defvar *loop-collection-cruft
*) ; for multiple COLLECTs (etc)
715 (eval-when (:compile-toplevel
#+movitz-loop
:load-toplevel
)
717 ;;;; Code Analysis Stuff
720 (defun loop-constant-fold-if-possible (form &optional expected-type
)
721 #+Genera
(declare (values new-form constantp constant-value
))
722 (let ((new-form form
) (constantp nil
) (constant-value nil
))
723 #+Genera
(setq new-form
(compiler:optimize-form form
*loop-macro-environment
*
725 :do-macro-expansion t
726 :do-named-constants t
729 :do-constant-folding t
731 constantp
(constantp new-form
*loop-macro-environment
*)
732 constant-value
(and constantp
(lt:evaluate-constant new-form
*loop-macro-environment
*)))
733 #-Genera
(when (setq constantp
(constantp new-form
))
734 (setq constant-value
(eval new-form
)))
735 (when (and constantp expected-type
)
736 (unless (typep constant-value expected-type
)
737 (loop-warn "The form ~S evaluated to ~S, which was not of the anticipated type ~S."
738 form constant-value expected-type
)
739 (setq constantp nil constant-value nil
)))
740 (values new-form constantp constant-value
)))
743 (defun loop-constantp (form)
744 #+Genera
(constantp form
*loop-macro-environment
*)
745 #-Genera
(constantp form
))
748 ;;;; LOOP Iteration Optimization
750 (defvar *loop-duplicate-code
*
754 (defvar *loop-iteration-flag-variable
*
755 (make-symbol "LOOP-NOT-FIRST-TIME"))
758 (defun loop-code-duplication-threshold (env)
759 (multiple-value-bind (speed space
) (loop-optimization-quantities env
)
760 (+ 40 (* (- speed space
) 10))))
763 (defun duplicatable-code-p (expr env
)
765 (let ((ans (estimate-code-size expr env
)))
766 (declare (fixnum ans
))
767 ;;@@@@ Use (DECLARATION-INFORMATION 'OPTIMIZE ENV) here to get an alist of
768 ;; optimize quantities back to help quantify how much code we are willing to
773 (defvar *special-code-sizes
*
774 '((return 0) (progn 0)
775 (null 1) (not 1) (eq 1) (car 1) (cdr 1)
776 (when 1) (unless 1) (if 1)
777 (caar 2) (cadr 2) (cdar 2) (cddr 2)
778 (caaar 3) (caadr 3) (cadar 3) (caddr 3) (cdaar 3) (cdadr 3) (cddar 3) (cdddr 3)
779 (caaaar 4) (caaadr 4) (caadar 4) (caaddr 4)
780 (cadaar 4) (cadadr 4) (caddar 4) (cadddr 4)
781 (cdaaar 4) (cdaadr 4) (cdadar 4) (cdaddr 4)
782 (cddaar 4) (cddadr 4) (cdddar 4) (cddddr 4)))
785 (defvar *estimate-code-size-punt
*
789 labels lambda let let
* locally
790 macrolet multiple-value-bind
798 (defun destructuring-size (x)
799 (do ((x x
(cdr x
)) (n 0 (+ (destructuring-size (car x
)) n
)))
800 ((atom x
) (+ n
(if (null x
) 0 1)))))
803 (defun estimate-code-size (x env
)
804 (catch 'estimate-code-size
805 (estimate-code-size-1 x env
)))
808 (defun estimate-code-size-1 (x env
)
809 (flet ((list-size (l)
812 (dolist (x l n
) (incf n
(estimate-code-size-1 x env
))))))
813 ;;@@@@ ???? (declare (function list-size (list) fixnum))
814 (cond ((constantp x
#+Genera env
) 1)
815 ((symbolp x
) (multiple-value-bind (new-form expanded-p
) (movitz::movitz-macroexpand-1 x env
)
816 (if expanded-p
(estimate-code-size-1 new-form env
) 1)))
817 ((atom x
) 1) ;??? self-evaluating???
819 (let ((fn (car x
)) (tem nil
) (n 0))
820 (declare (symbol fn
) (fixnum n
))
821 (macrolet ((f (overhead &optional
(args nil args-p
))
822 `(the fixnum
(+ (the fixnum
,overhead
)
823 (the fixnum
(list-size ,(if args-p args
'(cdr x
))))))))
824 (cond ((setq tem
(get fn
'estimate-code-size
))
827 (t (funcall tem x env
))))
828 ((setq tem
(assoc fn
*special-code-sizes
*)) (f (second tem
)))
830 ((eq fn
'compiler
:invisible-references
) (list-size (cddr x
)))
832 (dolist (clause (cdr x
) n
) (incf n
(list-size clause
)) (incf n
)))
834 (do ((l (cdr x
) (cdr l
))) ((null l
) n
)
835 (setq n
(+ n
(destructuring-size (car l
)) (estimate-code-size-1 (cadr l
) env
)))))
836 ((member fn
'(setq psetq
))
837 (do ((l (cdr x
) (cdr l
))) ((null l
) n
)
838 (setq n
(+ n
(estimate-code-size-1 (cadr l
) env
) 1))))
841 ;;This skirts the issue of implementationally-defined lambda macros
842 ;; by recognizing CL function names and nothing else.
843 (if (or (symbolp (cadr x
))
844 (and (consp (cadr x
)) (eq (caadr x
) 'setf
)))
846 (throw 'duplicatable-code-p nil
)))
847 ((eq fn
'multiple-value-setq
) (f (length (second x
)) (cddr x
)))
848 ((eq fn
'return-from
) (1+ (estimate-code-size-1 (third x
) env
)))
849 ((or (special-operator-p fn
) (member fn
*estimate-code-size-punt
*))
850 (throw 'estimate-code-size nil
))
851 (t (multiple-value-bind (new-form expanded-p
) (movitz::movitz-macroexpand-1 x env
)
853 (estimate-code-size-1 new-form env
)
855 (t (throw 'estimate-code-size nil
)))))
861 (defun loop-context ()
862 (do ((l *loop-source-context
* (cdr l
)) (new nil
(cons (car l
) new
)))
863 ((eq l
(cdr *loop-source-code
*)) (nreverse new
))))
866 (defun loop-error (format-string &rest format-args
)
867 #+movitz
(declare (dynamic-extent format-args
))
868 #+(or Genera CLOE
) (declare (dbg:error-reporter
))
869 #+Genera
(setq format-args
(copy-list format-args
)) ;Don't ask.
870 (error "~?~%Current LOOP context:~{ ~S~}." format-string format-args
(loop-context)))
873 (defun loop-warn (format-string &rest format-args
)
874 #+movitz
(declare (dynamic-extent format-args
))
875 (warn "~?~%Current LOOP context:~{ ~S~}." format-string format-args
(loop-context)))
878 (defun loop-check-data-type (specified-type required-type
879 &optional
(default-type required-type
))
880 (if (null specified-type
)
882 (multiple-value-bind (a b
) (subtypep specified-type required-type
)
884 (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
885 specified-type required-type
))
887 (loop-error "Specified data type ~S is not a subtype of ~S."
888 specified-type required-type
)))
895 (defun loop-translate (*loop-source-code
* *loop-macro-environment
* *loop-universe
*)
896 (let ((*loop-original-source-code
* *loop-source-code
*)
897 (*loop-source-context
* nil
)
898 (*loop-iteration-variables
* nil
)
899 (*loop-variables
* nil
)
900 (*loop-nodeclare
* nil
)
901 (*loop-named-variables
* nil
)
902 (*loop-declarations
* nil
)
903 (*loop-desetq-crocks
* nil
)
904 (*loop-bind-stack
* nil
)
905 (*loop-prologue
* nil
)
906 (*loop-wrappers
* nil
)
907 (*loop-before-loop
* nil
)
909 (*loop-emitted-body
* nil
)
910 (*loop-after-body
* nil
)
911 (*loop-epilogue
* nil
)
912 (*loop-after-epilogue
* nil
)
913 (*loop-final-value-culprit
* nil
)
914 (*loop-inside-conditional
* nil
)
915 (*loop-when-it-variable
* nil
)
916 (*loop-never-stepped-variable
* nil
)
918 (*loop-collection-cruft
* nil
))
919 (loop-iteration-driver)
921 (let ((answer `(loop-body
922 ,(nreverse *loop-prologue
*)
923 ,(nreverse *loop-before-loop
*)
924 ,(nreverse *loop-body
*)
925 ,(nreverse *loop-after-body
*)
926 ,(nreconc *loop-epilogue
* (nreverse *loop-after-epilogue
*)))))
928 (setq answer
`(block ,(pop *loop-names
*) ,answer
))
929 (unless *loop-names
* (return nil
)))
930 (dolist (entry *loop-bind-stack
*)
931 (let ((vars (first entry
))
932 (dcls (second entry
))
933 (crocks (third entry
))
934 (wrappers (fourth entry
)))
936 (setq answer
(append w
(list answer
))))
937 (when (or vars dcls crocks
)
938 (let ((forms (list answer
)))
939 ;;(when crocks (push crocks forms))
940 (when dcls
(push `(declare ,@dcls
) forms
))
941 (setq answer
`(,(cond ((not vars
) 'locally
)
942 (*loop-destructuring-hooks
* (first *loop-destructuring-hooks
*))
946 `((destructuring-bind ,@crocks
952 (defun loop-iteration-driver ()
953 (do () ((null *loop-source-code
*))
954 (let ((keyword (car *loop-source-code
*)) (tem nil
))
955 (cond ((not (symbolp keyword
))
956 (loop-error "~S found where LOOP keyword expected." keyword
))
957 (t (setq *loop-source-context
* *loop-source-code
*)
959 (cond ((setq tem
(loop-lookup-keyword keyword
(loop-universe-keywords *loop-universe
*)))
960 ;;It's a "miscellaneous" toplevel LOOP keyword (do, collect, named, etc.)
961 (apply (symbol-function (first tem
)) (rest tem
)))
962 ((setq tem
(loop-lookup-keyword keyword
(loop-universe-iteration-keywords *loop-universe
*)))
963 (loop-hack-iteration tem
))
964 ((loop-tmember keyword
'(and else
))
965 ;; Alternative is to ignore it, ie let it go around to the next keyword...
966 (loop-error "Secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
967 keyword
(car *loop-source-code
*) (cadr *loop-source-code
*)))
968 (t (loop-error "~S is an unknown keyword in LOOP macro." keyword
))))))))
972 (defun loop-pop-source ()
973 (if *loop-source-code
*
974 (pop *loop-source-code
*)
975 (loop-error "LOOP source code ran out when another token was expected.")))
978 (defun loop-get-progn ()
979 (do ((forms (list (loop-pop-source)) (cons (loop-pop-source) forms
))
980 (nextform (car *loop-source-code
*) (car *loop-source-code
*)))
982 (if (null (cdr forms
)) (car forms
) (cons 'progn
(nreverse forms
))))))
985 (defun loop-get-form ()
986 (if *loop-source-code
*
988 (loop-error "LOOP code ran out where a form was expected.")))
991 (defun loop-construct-return (form)
992 `(return-from ,(car *loop-names
*) ,form
))
995 (defun loop-pseudo-body (form)
996 (cond ((or *loop-emitted-body
* *loop-inside-conditional
*) (push form
*loop-body
*))
997 (t (push form
*loop-before-loop
*) (push form
*loop-after-body
*))))
999 (defun loop-emit-body (form)
1000 (setq *loop-emitted-body
* t
)
1001 (loop-pseudo-body form
))
1003 (defun loop-emit-final-value (form)
1004 (push (loop-construct-return form
) *loop-after-epilogue
*)
1005 (when *loop-final-value-culprit
*
1006 (loop-warn "LOOP clause is providing a value for the iteration,~@
1007 however one was already established by a ~S clause."
1008 *loop-final-value-culprit
*))
1009 (setq *loop-final-value-culprit
* (car *loop-source-context
*)))
1012 (defun loop-disallow-conditional (&optional kwd
)
1013 #+(or Genera CLOE
) (declare (dbg:error-reporter
))
1014 (when *loop-inside-conditional
*
1015 (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd
)))
1021 (defun loop-typed-init (data-type)
1022 (when (and data-type
(subtypep data-type
'number
))
1023 (if (or (subtypep data-type
'float
) (subtypep data-type
'(complex float
)))
1024 (coerce 0 data-type
)
1028 (defun loop-optional-type (&optional variable
)
1029 ;;No variable specified implies that no destructuring is permissible.
1030 (and *loop-source-code
* ;Don't get confused by NILs...
1031 (let ((z (car *loop-source-code
*)))
1032 (cond ((loop-tequal z
'of-type
)
1033 ;;This is the syntactically unambigous form in that the form of the
1034 ;; type specifier does not matter. Also, it is assumed that the
1035 ;; type specifier is unambiguously, and without need of translation,
1036 ;; a common lisp type specifier or pattern (matching the variable) thereof.
1041 ;;This is the (sort of) "old" syntax, even though we didn't used to support all of
1042 ;; these type symbols.
1043 (let ((type-spec (or (gethash z
(loop-universe-type-symbols *loop-universe
*))
1044 (gethash (symbol-name z
) (loop-universe-type-keywords *loop-universe
*)))))
1049 ;;This is our sort-of old syntax. But this is only valid for when we are destructuring,
1050 ;; so we will be compulsive (should we really be?) and require that we in fact be
1051 ;; doing variable destructuring here. We must translate the old keyword pattern typespec
1052 ;; into a fully-specified pattern of real type specifiers here.
1053 (if (consp variable
)
1056 "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected."
1058 (loop-error "~S found where a LOOP keyword or LOOP type keyword expected." z
))
1060 (labels ((translate (k v
)
1061 (cond ((null k
) nil
)
1064 (or (gethash k
(loop-universe-type-symbols *loop-universe
*))
1065 (gethash (symbol-name k
) (loop-universe-type-keywords *loop-universe
*))
1067 "Destructuring type pattern ~S contains unrecognized type keyword ~S."
1072 "Destructuring type pattern ~S doesn't match variable pattern ~S."
1074 (t (cons (translate (car k
) (car v
)) (translate (cdr k
) (cdr v
))))))
1076 (if (atom v
) typ
(cons (replicate typ
(car v
)) (replicate typ
(cdr v
))))))
1077 (translate z variable
)))))))
1084 (defun loop-bind-block ()
1085 (when (or *loop-variables
* *loop-declarations
* *loop-wrappers
*)
1086 (push (list (nreverse *loop-variables
*) *loop-declarations
* *loop-desetq-crocks
* *loop-wrappers
*)
1088 (setq *loop-variables
* nil
1089 *loop-declarations
* nil
1090 *loop-desetq-crocks
* nil
1091 *loop-wrappers
* nil
)))
1094 (defun loop-make-variable (name initialization dtype
&optional iteration-variable-p
)
1096 (cond ((not (null initialization
))
1097 (push (list (setq name
(loop-gentemp 'loop-ignore-
))
1100 (push `(ignore ,name
) *loop-declarations
*))))
1102 (cond (iteration-variable-p
1103 (if (member name
*loop-iteration-variables
*)
1104 (loop-error "Duplicated LOOP iteration variable ~S." name
)
1105 (push name
*loop-iteration-variables
*)))
1106 ((assoc name
*loop-variables
*)
1107 (loop-error "Duplicated variable ~S in LOOP parallel binding." name
)))
1108 (unless (symbolp name
)
1109 (loop-error "Bad variable ~S somewhere in LOOP." name
))
1110 (loop-declare-variable name dtype
)
1111 ;; We use ASSOC on this list to check for duplications (above),
1112 ;; so don't optimize out this list:
1113 (push (list name
(or initialization
(loop-typed-init dtype
)))
1116 (cond (*loop-destructuring-hooks
*
1117 (loop-declare-variable name dtype
)
1118 (push (list name initialization
) *loop-variables
*))
1119 (t (let ((newvar (loop-gentemp 'loop-destructure-
)))
1120 (push (list newvar initialization
) *loop-variables
*)
1121 ;; *LOOP-DESETQ-CROCKS* gathered in reverse order.
1122 (setq *loop-desetq-crocks
*
1123 (list* name newvar
*loop-desetq-crocks
*))
1125 (loop-make-variable name nil dtype iteration-variable-p
)))))
1126 (t (let ((tcar nil
) (tcdr nil
))
1127 (if (atom dtype
) (setq tcar
(setq tcdr dtype
))
1128 (setq tcar
(car dtype
) tcdr
(cdr dtype
)))
1129 (loop-make-variable (car name
) nil tcar iteration-variable-p
)
1130 (loop-make-variable (cdr name
) nil tcdr iteration-variable-p
))))
1134 (defun loop-make-iteration-variable (name initialization dtype
)
1135 (loop-make-variable name initialization dtype t
))
1138 (defun loop-declare-variable (name dtype
)
1139 (cond ((or (null name
) (null dtype
) (eq dtype t
)) nil
)
1141 (unless (or (eq dtype t
) (member (the symbol name
) *loop-nodeclare
*))
1142 (let ((dtype #-cmu dtype
1144 (let ((init (loop-typed-init dtype
)))
1145 (if (typep init dtype
)
1147 `(or (member ,init
) ,dtype
)))))
1148 (push `(type ,dtype
,name
) *loop-declarations
*))))
1150 (cond ((consp dtype
)
1151 (loop-declare-variable (car name
) (car dtype
))
1152 (loop-declare-variable (cdr name
) (cdr dtype
)))
1153 (t (loop-declare-variable (car name
) dtype
)
1154 (loop-declare-variable (cdr name
) dtype
))))
1155 (t (error "Invalid LOOP variable passed in: ~S." name
))))
1158 (defun loop-maybe-bind-form (form data-type
)
1159 (if (loop-constantp form
)
1161 (loop-make-variable (loop-gentemp 'loop-bind-
) form data-type
)))
1165 (defun loop-do-if (for negatep
)
1166 (let ((form (loop-get-form)) (*loop-inside-conditional
* t
) (it-p nil
))
1167 (flet ((get-clause (for)
1168 (do ((body nil
)) (nil)
1169 (let ((key (car *loop-source-code
*)) (*loop-body
* nil
) data
)
1170 (cond ((not (symbolp key
))
1172 "~S found where keyword expected getting LOOP clause after ~S."
1174 (t (setq *loop-source-context
* *loop-source-code
*)
1176 (when (loop-tequal (car *loop-source-code
*) 'it
)
1177 (setq *loop-source-code
*
1178 (cons (or it-p
(setq it-p
(loop-when-it-variable)))
1179 (cdr *loop-source-code
*))))
1180 (cond ((or (not (setq data
(loop-lookup-keyword
1181 key
(loop-universe-keywords *loop-universe
*))))
1182 (progn (apply (symbol-function (car data
)) (cdr data
))
1183 (null *loop-body
*)))
1185 "~S does not introduce a LOOP clause that can follow ~S."
1187 (t (setq body
(nreconc *loop-body
* body
)))))))
1188 (if (loop-tequal (car *loop-source-code
*) :and
)
1190 (return (if (cdr body
) `(progn ,@(nreverse body
)) (car body
)))))))
1191 (let ((then (get-clause for
))
1192 (else (when (loop-tequal (car *loop-source-code
*) :else
)
1194 (list (get-clause :else
)))))
1195 (when (loop-tequal (car *loop-source-code
*) :end
)
1197 (when it-p
(setq form
`(setq ,it-p
,form
)))
1199 `(if ,(if negatep
`(not ,form
) form
)
1204 (defun loop-do-initially ()
1205 (loop-disallow-conditional :initially
)
1206 (push (loop-get-progn) *loop-prologue
*))
1208 (defun loop-do-finally ()
1209 (loop-disallow-conditional :finally
)
1210 (push (loop-get-progn) *loop-epilogue
*))
1212 (defun loop-do-do ()
1213 (loop-emit-body (loop-get-progn)))
1215 (defun loop-do-named ()
1216 (let ((name (loop-pop-source)))
1217 (unless (symbolp name
)
1218 (loop-error "~S is an invalid name for your LOOP." name
))
1219 (when (or *loop-before-loop
* *loop-body
* *loop-after-epilogue
* *loop-inside-conditional
*)
1220 (loop-error "The NAMED ~S clause occurs too late." name
))
1222 (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1223 (car *loop-names
*) name
))
1224 (setq *loop-names
* (list name nil
))))
1226 (defun loop-do-return ()
1227 (loop-emit-body (loop-construct-return (loop-get-form))))
1232 ;;;; Value Accumulation: List
1237 (eval-when (:compile-toplevel
#+movitz-loop
:load-toplevel
)
1239 (defun loop-get-collection-info (collector class default-type
)
1240 (let ((form (loop-get-form))
1241 (dtype (and (not (loop-universe-ansi *loop-universe
*)) (loop-optional-type)))
1242 (name (when (loop-tequal (car *loop-source-code
*) 'into
)
1244 (loop-pop-source))))
1245 (when (not (symbolp name
))
1246 (loop-error "Value accumulation recipient name, ~S, is not a symbol." name
))
1248 (setq dtype
(or (loop-optional-type) default-type
)))
1249 (let ((cruft (find (the symbol name
) *loop-collection-cruft
*
1250 :key
#'loop-collector-name
)))
1252 (push (setq cruft
(make-loop-collector
1253 :name name
:class class
1254 :history
(list collector
) :dtype dtype
))
1255 *loop-collection-cruft
*))
1256 (t (unless (eq (loop-collector-class cruft
) class
)
1258 "Incompatible kinds of LOOP value accumulation specified for collecting~@
1259 ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S."
1260 name
(car (loop-collector-history cruft
)) collector
))
1261 (unless (equal dtype
(loop-collector-dtype cruft
))
1263 "Unequal datatypes specified in different LOOP value accumulations~@
1264 into ~S: ~S and ~S."
1265 name dtype
(loop-collector-dtype cruft
))
1266 (when (eq (loop-collector-dtype cruft
) t
)
1267 (setf (loop-collector-dtype cruft
) dtype
)))
1268 (push collector
(loop-collector-history cruft
))))
1269 (values cruft form
))))
1272 (defun loop-list-collection (specifically) ;NCONC, LIST, or APPEND
1273 (multiple-value-bind (lc form
) (loop-get-collection-info specifically
'list
'list
)
1274 (let ((tempvars (loop-collector-tempvars lc
)))
1276 (setf (loop-collector-tempvars lc
)
1277 (setq tempvars
(list* (loop-gentemp 'loop-list-head-
)
1278 (loop-gentemp 'loop-list-tail-
)
1279 (and (loop-collector-name lc
)
1280 (list (loop-collector-name lc
))))))
1281 (push `(with-loop-list-collection-head ,tempvars
) *loop-wrappers
*)
1282 (unless (loop-collector-name lc
)
1283 (loop-emit-final-value `(loop-collect-answer ,(car tempvars
) ,@(cddr tempvars
)))))
1285 (list (setq form
`(list ,form
)))
1287 (append (unless (and (consp form
) (eq (car form
) 'list
))
1288 (setq form
`(loop-copylist* ,form
)))))
1289 (loop-emit-body `(loop-collect-rplacd ,tempvars
,form
)))))
1292 ;;;; Value Accumulation: max, min, sum, count.
1296 (defun loop-sum-collection (specifically required-type default-type
) ;SUM, COUNT
1297 (multiple-value-bind (lc form
)
1298 (loop-get-collection-info specifically
'sum default-type
)
1299 (loop-check-data-type (loop-collector-dtype lc
) required-type
)
1300 (let ((tempvars (loop-collector-tempvars lc
)))
1302 (setf (loop-collector-tempvars lc
)
1303 (setq tempvars
(list (loop-make-variable
1304 (or (loop-collector-name lc
)
1305 (loop-gentemp 'loop-sum-
))
1306 nil
(loop-collector-dtype lc
)))))
1307 (unless (loop-collector-name lc
)
1308 (loop-emit-final-value (car (loop-collector-tempvars lc
)))))
1310 (if (eq specifically
'count
)
1312 (setq ,(car tempvars
)
1313 ,(hide-variable-reference t
(car tempvars
) `(1+ ,(car tempvars
)))))
1314 `(setq ,(car tempvars
)
1315 (+ ,(hide-variable-reference t
(car tempvars
) (car tempvars
))
1320 (defun loop-maxmin-collection (specifically)
1321 (multiple-value-bind (lc form
)
1322 (loop-get-collection-info specifically
'maxmin
*loop-real-data-type
*)
1323 (loop-check-data-type (loop-collector-dtype lc
) *loop-real-data-type
*)
1324 (let ((data (loop-collector-data lc
)))
1326 (setf (loop-collector-data lc
)
1327 (setq data
(make-loop-minimax
1328 (or (loop-collector-name lc
) (loop-gentemp 'loop-maxmin-
))
1329 (loop-collector-dtype lc
))))
1330 (unless (loop-collector-name lc
)
1331 (loop-emit-final-value (loop-minimax-answer-variable data
))))
1332 (loop-note-minimax-operation specifically data
)
1333 (push `(with-minimax-value ,data
) *loop-wrappers
*)
1334 (loop-emit-body `(loop-accumulate-minimax-value ,data
,specifically
,form
))
1338 ;;;; Value Accumulation: Aggregate Booleans
1340 ;;;ALWAYS and NEVER.
1341 ;;; Under ANSI these are not permitted to appear under conditionalization.
1342 (defun loop-do-always (restrictive negate
)
1343 (let ((form (loop-get-form)))
1344 (when restrictive
(loop-disallow-conditional))
1345 (loop-emit-body `(,(if negate
'when
'unless
) ,form
1346 ,(loop-construct-return nil
)))
1347 (loop-emit-final-value t
)))
1352 ;;; Under ANSI this is not permitted to appear under conditionalization.
1353 (defun loop-do-thereis (restrictive)
1354 (when restrictive
(loop-disallow-conditional))
1355 (loop-emit-body `(when (setq ,(loop-when-it-variable) ,(loop-get-form))
1356 ,(loop-construct-return *loop-when-it-variable
*))))
1359 (defun loop-do-while (negate kwd
&aux
(form (loop-get-form)))
1360 (loop-disallow-conditional kwd
)
1361 (loop-pseudo-body `(,(if negate
'when
'unless
) ,form
(go end-loop
))))
1364 (defun loop-do-with ()
1365 (loop-disallow-conditional :with
)
1366 (do ((var) (val) (dtype)) (nil)
1367 (setq var
(loop-pop-source)
1368 dtype
(loop-optional-type var
)
1369 val
(cond ((loop-tequal (car *loop-source-code
*) :=)
1373 (loop-make-variable var val dtype
)
1374 (if (loop-tequal (car *loop-source-code
*) :and
)
1376 (return (loop-bind-block)))))
1379 ;;;; The iteration driver
1381 (defun loop-hack-iteration (entry)
1382 (flet ((make-endtest (list-of-forms)
1383 (cond ((null list-of-forms
) nil
)
1384 ((member t list-of-forms
) '(go end-loop
))
1385 (t `(when ,(if (null (cdr (setq list-of-forms
(nreverse list-of-forms
))))
1387 (cons 'or list-of-forms
))
1389 (do ((pre-step-tests nil
)
1391 (post-step-tests nil
)
1393 (pre-loop-pre-step-tests nil
)
1394 (pre-loop-steps nil
)
1395 (pre-loop-post-step-tests nil
)
1396 (pre-loop-pseudo-steps nil
)
1399 ;; Note we collect endtests in reverse order, but steps in correct
1400 ;; order. MAKE-ENDTEST does the nreverse for us.
1401 (setq tem
(setq data
(apply (symbol-function (first entry
)) (rest entry
))))
1402 (and (car tem
) (push (car tem
) pre-step-tests
))
1403 (setq steps
(nconc steps
(loop-copylist* (car (setq tem
(cdr tem
))))))
1404 (and (car (setq tem
(cdr tem
))) (push (car tem
) post-step-tests
))
1405 (setq pseudo-steps
(nconc pseudo-steps
(loop-copylist* (car (setq tem
(cdr tem
))))))
1406 (setq tem
(cdr tem
))
1407 (when *loop-emitted-body
*
1408 (loop-error "Iteration in LOOP follows body code."))
1409 (unless tem
(setq tem data
))
1410 (when (car tem
) (push (car tem
) pre-loop-pre-step-tests
))
1411 (setq pre-loop-steps
(nconc pre-loop-steps
(loop-copylist* (car (setq tem
(cdr tem
))))))
1412 (when (car (setq tem
(cdr tem
))) (push (car tem
) pre-loop-post-step-tests
))
1413 (setq pre-loop-pseudo-steps
(nconc pre-loop-pseudo-steps
(loop-copylist* (cadr tem
))))
1414 (unless (loop-tequal (car *loop-source-code
*) :and
)
1415 (setq *loop-before-loop
* (list* (loop-make-desetq pre-loop-pseudo-steps
)
1416 (make-endtest pre-loop-post-step-tests
)
1417 (loop-make-psetq pre-loop-steps
)
1418 (make-endtest pre-loop-pre-step-tests
)
1420 *loop-after-body
* (list* (loop-make-desetq pseudo-steps
)
1421 (make-endtest post-step-tests
)
1422 (loop-make-psetq steps
)
1423 (make-endtest pre-step-tests
)
1427 (loop-pop-source) ; flush the "AND"
1428 (when (and (not (loop-universe-implicit-for-required *loop-universe
*))
1429 (setq tem
(loop-lookup-keyword
1430 (car *loop-source-code
*)
1431 (loop-universe-iteration-keywords *loop-universe
*))))
1432 ;;Latest ANSI clarification is that the FOR/AS after the AND must NOT be supplied.
1434 (setq entry tem
)))))
1437 ;;;; Main Iteration Drivers
1440 ;FOR variable keyword ..args..
1441 (defun loop-do-for ()
1442 (let* ((var (loop-pop-source))
1443 (data-type (loop-optional-type var
))
1444 (keyword (loop-pop-source))
1447 (setq first-arg
(loop-get-form))
1448 (unless (and (symbolp keyword
)
1449 (setq tem
(loop-lookup-keyword
1451 (loop-universe-for-keywords *loop-universe
*))))
1452 (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP." keyword
))
1453 (apply (car tem
) var first-arg data-type
(cdr tem
))))
1456 (defun loop-do-repeat ()
1457 (let ((form (loop-get-form))
1458 (type (loop-check-data-type (loop-optional-type) *loop-real-data-type
*)))
1459 (when (and (consp form
) (eq (car form
) 'the
) (subtypep (second form
) type
))
1460 (setq type
(second form
)))
1461 (multiple-value-bind (number constantp value
)
1462 (loop-constant-fold-if-possible form type
)
1463 (cond ((and constantp
(<= value
1)) `(t () () () ,(<= value
0) () () ()))
1464 (t (let ((var (loop-make-variable (loop-gentemp 'loop-repeat-
) number type
)))
1466 `((not (plusp (setq ,var
(1- ,var
)))) () () () () () () ())
1467 `((minusp (setq ,var
(1- ,var
))) () () ()))))))))
1470 (defun loop-when-it-variable ()
1471 (or *loop-when-it-variable
*
1472 (setq *loop-when-it-variable
*
1473 (loop-make-variable (loop-gentemp 'loop-it-
) nil nil
))))
1476 ;;;; Various FOR/AS Subdispatches
1479 ;;;ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when the THEN
1480 ;;; is omitted (other than being more stringent in its placement), and like
1481 ;;; the old "FOR x FIRST y THEN z" when the THEN is present. I.e., the first
1482 ;;; initialization occurs in the loop body (first-step), not in the variable binding
1484 (defun loop-ansi-for-equals (var val data-type
)
1485 (loop-make-iteration-variable var nil data-type
)
1486 (cond ((loop-tequal (car *loop-source-code
*) :then
)
1487 ;;Then we are the same as "FOR x FIRST y THEN z".
1489 `(() (,var
,(loop-get-form)) () ()
1490 () (,var
,val
) () ()))
1491 (t ;;We are the same as "FOR x = y".
1492 `(() (,var
,val
) () ()))))
1495 (defun loop-for-across (var val data-type
)
1496 (loop-make-iteration-variable var nil data-type
)
1497 (let ((vector-var (loop-gentemp 'loop-across-vector-
))
1498 (index-var (loop-gentemp 'loop-across-index-
)))
1499 (multiple-value-bind (vector-form constantp vector-value
)
1500 (loop-constant-fold-if-possible val
'vector
)
1502 vector-var vector-form
1503 (if (and (consp vector-form
) (eq (car vector-form
) 'the
))
1506 #+Genera
(push `(system:array-register
,vector-var
) *loop-declarations
*)
1507 (loop-make-variable index-var
0 'fixnum
)
1509 (length-form (cond ((not constantp
)
1510 (let ((v (loop-gentemp 'loop-across-limit-
)))
1511 (push `(setq ,v
(length ,vector-var
)) *loop-prologue
*)
1512 (loop-make-variable v
0 'fixnum
)))
1513 (t (setq length
(length vector-value
)))))
1514 (first-test `(>= ,index-var
,length-form
))
1515 (other-test first-test
)
1516 (step `(,var
(aref ,vector-var
,index-var
)))
1517 (pstep `(,index-var
(1+ ,index-var
))))
1518 (declare (fixnum length
))
1520 (setq first-test
(= length
0))
1522 (setq other-test t
)))
1523 `(,other-test
,step
() ,pstep
1524 ,@(and (not (eq first-test other-test
)) `(,first-test
,step
() ,pstep
)))))))
1531 (defun loop-list-step (listvar)
1532 ;;We are not equipped to analyze whether 'FOO is the same as #'FOO here in any
1533 ;; sensible fashion, so let's give an obnoxious warning whenever 'FOO is used
1534 ;; as the stepping function.
1535 ;;While a Discerning Compiler may deal intelligently with (funcall 'foo ...), not
1536 ;; recognizing FOO may defeat some LOOP optimizations.
1537 (let ((stepper (cond ((loop-tequal (car *loop-source-code
*) :by
)
1540 (t '(function cdr
)))))
1541 (cond ((and (consp stepper
) (eq (car stepper
) 'quote
))
1542 (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1543 (values `(funcall ,stepper
,listvar
) nil
))
1544 ((and (consp stepper
) (eq (car stepper
) 'function
))
1545 (values (list (cadr stepper
) listvar
) (cadr stepper
)))
1546 (t (values `(funcall ,(loop-make-variable (loop-gentemp 'loop-fn-
) stepper
'function
)
1551 (defun loop-for-on (var val data-type
)
1552 (multiple-value-bind (list constantp list-value
) (loop-constant-fold-if-possible val
)
1553 (let ((listvar var
))
1554 (cond ((and var
(symbolp var
)) (loop-make-iteration-variable var list data-type
))
1555 (t (loop-make-variable (setq listvar
(loop-gentemp)) list t
)
1556 (loop-make-iteration-variable var nil data-type
)))
1557 (multiple-value-bind (list-step step-function
) (loop-list-step listvar
)
1558 (declare #+(and (not LOOP-Prefer-POP
) (not CLOE
)) (ignore step-function
))
1559 ;;@@@@ The CLOE problem above has to do with bug in macroexpansion of multiple-value-bind.
1560 (let* ((first-endtest
1561 (hide-variable-reference
1564 ;; the following should use `atom' instead of `endp', per
1567 (other-endtest first-endtest
))
1568 (when (and constantp
(listp list-value
))
1569 (setq first-endtest
(null list-value
)))
1570 (cond ((eq var listvar
)
1571 ;;Contour of the loop is different because we use the user's variable...
1572 `(() (,listvar
,(hide-variable-reference t listvar list-step
)) ,other-endtest
1573 () () () ,first-endtest
()))
1576 (let ((n (cdr (assoc step-function
'((cdr .
1) (cddr .
2)
1577 (cdddr .
3) (cddddr .
4))))))
1578 (and n
(do ((l var
(cdr l
)) (i 0 (1+ i
)))
1579 ((atom l
) (and (null l
) (= i n
)))
1580 (declare (fixnum i
))))))
1581 (let ((step (mapcan #'(lambda (x) (list x
`(pop ,listvar
))) var
)))
1582 `(,other-endtest
() () ,step
,first-endtest
() () ,step
)))
1583 (t (let ((step `(,var
,listvar
)) (pseudo `(,listvar
,list-step
)))
1584 `(,other-endtest
,step
() ,pseudo
1585 ,@(and (not (eq first-endtest other-endtest
))
1586 `(,first-endtest
,step
() ,pseudo
)))))))))))
1589 (defun loop-for-in (var val data-type
)
1590 (multiple-value-bind (list constantp list-value
) (loop-constant-fold-if-possible val
)
1591 (let ((listvar (loop-gentemp 'loop-list-
)))
1592 (loop-make-iteration-variable var nil data-type
)
1593 (loop-make-variable listvar list
'list
)
1594 (multiple-value-bind (list-step step-function
) (loop-list-step listvar
)
1595 #-LOOP-Prefer-POP
(declare (ignore step-function
))
1596 (let* ((first-endtest `(endp ,listvar
))
1597 (other-endtest first-endtest
)
1598 (step `(,var
(car ,listvar
)))
1599 (pseudo-step `(,listvar
,list-step
)))
1600 (when (and constantp
(listp list-value
))
1601 (setq first-endtest
(null list-value
)))
1602 #+LOOP-Prefer-POP
(when (eq step-function
'cdr
)
1603 (setq step
`(,var
(pop ,listvar
)) pseudo-step nil
))
1604 `(,other-endtest
,step
() ,pseudo-step
1605 ,@(and (not (eq first-endtest other-endtest
))
1606 `(,first-endtest
,step
() ,pseudo-step
))))))))
1609 ;;;; Iteration Paths
1614 (defun add-loop-path (names function universe
&key preposition-groups inclusive-permitted user-data
)
1615 (unless (listp names
) (setq names
(list names
)))
1616 ;; Can't do this due to CLOS bootstrapping problems.
1617 #-
(or Genera
(and CLOE Source-Bootstrap
)) (check-type universe loop-universe
)
1618 (let ((ht (loop-universe-path-keywords universe
))
1620 :names
(mapcar #'symbol-name names
)
1622 :user-data user-data
1623 :preposition-groups
(mapcar #'(lambda (x) (if (listp x
) x
(list x
))) preposition-groups
)
1624 :inclusive-permitted inclusive-permitted
)))
1625 (dolist (name names
) (setf (gethash (symbol-name name
) ht
) lp
))
1629 ;;; Note: path functions are allowed to use loop-make-variable, hack
1630 ;;; the prologue, etc.
1631 (defun loop-for-being (var val data-type
)
1632 ;; FOR var BEING each/the pathname prep-phrases using-stuff...
1633 ;; each/the = EACH or THE. Not clear if it is optional, so I guess we'll warn.
1638 (initial-prepositions nil
))
1639 (cond ((loop-tmember val
'(:each
:the
)) (setq path
(loop-pop-source)))
1640 ((loop-tequal (car *loop-source-code
*) :and
)
1643 (unless (loop-tmember (car *loop-source-code
*) '(:its
:each
:his
:her
))
1644 (loop-error "~S found where ITS or EACH expected in LOOP iteration path syntax."
1645 (car *loop-source-code
*)))
1647 (setq path
(loop-pop-source))
1648 (setq initial-prepositions
`((:in
,val
))))
1649 (t (loop-error "Unrecognizable LOOP iteration path syntax. Missing EACH or THE?")))
1650 (cond ((not (symbolp path
))
1651 (loop-error "~S found where a LOOP iteration path name was expected." path
))
1652 ((not (setq data
(loop-lookup-keyword path
(loop-universe-path-keywords *loop-universe
*))))
1653 (loop-error "~S is not the name of a LOOP iteration path." path
))
1654 ((and inclusive
(not (loop-path-inclusive-permitted data
)))
1655 (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path
)))
1656 (let ((fun (loop-path-function data
))
1657 (preps (nconc initial-prepositions
1658 (loop-collect-prepositional-phrases (loop-path-preposition-groups data
) t
)))
1659 (user-data (loop-path-user-data data
)))
1660 (when (symbolp fun
) (setq fun
(symbol-function fun
)))
1661 (setq stuff
(if inclusive
1662 (apply fun var data-type preps
:inclusive t user-data
)
1663 (apply fun var data-type preps user-data
))))
1664 (when *loop-named-variables
*
1665 (loop-error "Unused USING variables: ~S." *loop-named-variables
*))
1666 ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back). Protect the system from the user
1667 ;; and the user from himself.
1668 (unless (member (length stuff
) '(6 10))
1669 (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1671 (do ((l (car stuff
) (cdr l
)) (x)) ((null l
))
1672 (if (atom (setq x
(car l
)))
1673 (loop-make-iteration-variable x nil nil
)
1674 (loop-make-iteration-variable (car x
) (cadr x
) (caddr x
))))
1675 (setq *loop-prologue
* (nconc (reverse (cadr stuff
)) *loop-prologue
*))
1680 ;;;INTERFACE: Lucid, exported.
1681 ;;; i.e., this is part of our extended ansi-loop interface.
1682 (defun named-variable (name)
1683 (let ((tem (loop-tassoc name
*loop-named-variables
*)))
1684 (declare (list tem
))
1685 (cond ((null tem
) (values (loop-gentemp) nil
))
1686 (t (setq *loop-named-variables
* (delete tem
*loop-named-variables
*))
1687 (values (cdr tem
) t
)))))
1690 (defun loop-collect-prepositional-phrases (preposition-groups &optional USING-allowed initial-phrases
)
1691 (flet ((in-group-p (x group
) (car (loop-tmember x group
))))
1693 (prepositional-phrases initial-phrases
)
1694 (this-group nil nil
)
1696 (disallowed-prepositions
1697 (mapcan #'(lambda (x)
1699 (find (car x
) preposition-groups
:test
#'in-group-p
)))
1701 (used-prepositions (mapcar #'car initial-phrases
)))
1702 ((null *loop-source-code
*) (nreverse prepositional-phrases
))
1703 (declare (symbol this-prep
))
1704 (setq token
(car *loop-source-code
*))
1705 (dolist (group preposition-groups
)
1706 (when (setq this-prep
(in-group-p token group
))
1707 (return (setq this-group group
))))
1709 (when (member this-prep disallowed-prepositions
)
1711 (if (member this-prep used-prepositions
)
1712 "A ~S prepositional phrase occurs multiply for some LOOP clause."
1713 "Preposition ~S used when some other preposition has subsumed it.")
1715 (setq used-prepositions
(if (listp this-group
)
1716 (append this-group used-prepositions
)
1717 (cons this-group used-prepositions
)))
1719 (push (list this-prep
(loop-get-form)) prepositional-phrases
))
1720 ((and USING-allowed
(loop-tequal token
'using
))
1722 (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1725 (not (null (cddr z
)))
1726 (not (symbolp (car z
)))
1727 (and (cadr z
) (not (symbolp (cadr z
)))))
1728 (loop-error "~S bad variable pair in path USING phrase." z
))
1730 (if (setq tem
(loop-tassoc (car z
) *loop-named-variables
*))
1732 "The variable substitution for ~S occurs twice in a USING phrase,~@
1734 (car z
) (cadr z
) (cadr tem
))
1735 (push (cons (car z
) (cadr z
)) *loop-named-variables
*)))
1736 (when (or (null *loop-source-code
*) (symbolp (car *loop-source-code
*)))
1738 (t (return (nreverse prepositional-phrases
)))))))
1741 ;;;; Master Sequencer Function
1744 (defun loop-sequencer (indexv indexv-type indexv-user-specified-p
1745 variable variable-type
1746 sequence-variable sequence-type
1747 step-hack default-top
1749 (let ((endform nil
) ;Form (constant or variable) with limit value.
1750 (sequencep nil
) ;T if sequence arg has been provided.
1751 (testfn nil
) ;endtest function
1752 (test nil
) ;endtest form.
1753 (stepby (1+ (or (loop-typed-init indexv-type
) 0))) ;Our increment.
1754 (stepby-constantp t
)
1755 (step nil
) ;step form.
1756 (dir nil
) ;Direction of stepping: NIL, :UP, :DOWN.
1757 (inclusive-iteration nil
) ;T if include last index.
1758 (start-given nil
) ;T when prep phrase has specified start
1760 (start-constantp nil
)
1761 (limit-given nil
) ;T when prep phrase has specified end
1762 (limit-constantp nil
)
1765 (when variable
(loop-make-iteration-variable variable nil variable-type
))
1766 (do ((l prep-phrases
(cdr l
)) (prep) (form) (odir)) ((null l
))
1767 (setq prep
(caar l
) form
(cadar l
))
1771 (loop-make-variable sequence-variable form sequence-type
))
1772 ((:from
:downfrom
:upfrom
)
1773 (setq start-given t
)
1774 (cond ((eq prep
:downfrom
) (setq dir
':down
))
1775 ((eq prep
:upfrom
) (setq dir
':up
)))
1776 (multiple-value-setq (form start-constantp start-value
)
1777 (loop-constant-fold-if-possible form indexv-type
))
1778 (setq indexv
(loop-make-iteration-variable indexv form indexv-type
)))
1779 ((:upto
:to
:downto
:above
:below
)
1780 (cond ((loop-tequal prep
:upto
) (setq inclusive-iteration
(setq dir
':up
)))
1781 ((loop-tequal prep
:to
) (setq inclusive-iteration t
))
1782 ((loop-tequal prep
:downto
) (setq inclusive-iteration
(setq dir
':down
)))
1783 ((loop-tequal prep
:above
) (setq dir
':down
))
1784 ((loop-tequal prep
:below
) (setq dir
':up
)))
1785 (setq limit-given t
)
1786 (multiple-value-setq (form limit-constantp limit-value
)
1787 (loop-constant-fold-if-possible form indexv-type
))
1788 (setq endform
(if limit-constantp
1791 (loop-gentemp 'loop-limit-
) form indexv-type
))))
1793 (multiple-value-setq (form stepby-constantp stepby
)
1794 (loop-constant-fold-if-possible form indexv-type
))
1795 (unless stepby-constantp
1796 (loop-make-variable (setq stepby
(loop-gentemp 'loop-step-by-
)) form indexv-type
)))
1798 "~S invalid preposition in sequencing or sequence path.~@
1799 Invalid prepositions specified in iteration path descriptor or something?"
1801 (when (and odir dir
(not (eq dir odir
)))
1802 (loop-error "Conflicting stepping directions in LOOP sequencing path"))
1804 (when (and sequence-variable
(not sequencep
))
1805 (loop-error "Missing OF or IN phrase in sequence path"))
1806 ;; Now fill in the defaults.
1808 (loop-make-iteration-variable
1810 (setq start-constantp t start-value
(or (loop-typed-init indexv-type
) 0))
1812 (cond ((member dir
'(nil :up
))
1813 (when (or limit-given default-top
)
1815 (loop-make-variable (setq endform
(loop-gentemp 'loop-seq-limit-
))
1817 (push `(setq ,endform
,default-top
) *loop-prologue
*))
1818 (setq testfn
(if inclusive-iteration
'> '>=)))
1819 (setq step
(if (eql stepby
1) `(1+ ,indexv
) `(+ ,indexv
,stepby
))))
1820 (t (unless start-given
1822 (loop-error "Don't know where to start stepping."))
1823 (push `(setq ,indexv
(1- ,default-top
)) *loop-prologue
*))
1824 (when (and default-top
(not endform
))
1825 (setq endform
(loop-typed-init indexv-type
) inclusive-iteration t
))
1826 (when endform
(setq testfn
(if inclusive-iteration
'< '<=)))
1827 (setq step
(if (eql stepby
1) `(1- ,indexv
) `(- ,indexv
,stepby
)))))
1828 (when testfn
(setq test
(hide-variable-reference t indexv
`(,testfn
,indexv
,endform
))))
1830 (setq step-hack
`(,variable
,(hide-variable-reference indexv-user-specified-p indexv step-hack
))))
1831 (let ((first-test test
) (remaining-tests test
))
1832 (when (and stepby-constantp start-constantp limit-constantp
)
1833 (when (setq first-test
(funcall (symbol-function testfn
) start-value limit-value
))
1834 (setq remaining-tests t
)))
1835 `(() (,indexv
,(hide-variable-reference t indexv step
)) ,remaining-tests
,step-hack
1836 () () ,first-test
,step-hack
))))
1839 ;;;; Interfaces to the Master Sequencer
1843 (defun loop-for-arithmetic (var val data-type kwd
)
1845 var
(loop-check-data-type data-type
*loop-real-data-type
*) t
1846 nil nil nil nil nil nil
1847 (loop-collect-prepositional-phrases
1848 '((:from
:upfrom
:downfrom
) (:to
:upto
:downto
:above
:below
) (:by
))
1849 nil
(list (list kwd val
)))))
1852 (defun loop-sequence-elements-path (variable data-type prep-phrases
1853 &key fetch-function size-function sequence-type element-type
)
1854 (multiple-value-bind (indexv indexv-user-specified-p
) (named-variable 'index
)
1855 (let ((sequencev (named-variable 'sequence
)))
1856 #+Genera
(when (and sequencev
1859 (subtypep sequence-type
'vector
)
1860 (not (member (the symbol sequencev
) *loop-nodeclare
*)))
1861 (push `(sys:array-register
,sequencev
) *loop-declarations
*))
1862 (list* nil nil
; dummy bindings and prologue
1864 indexv
'fixnum indexv-user-specified-p
1865 variable
(or data-type element-type
)
1866 sequencev sequence-type
1867 `(,fetch-function
,sequencev
,indexv
) `(,size-function
,sequencev
)
1871 ;;;; Builtin LOOP Iteration Paths
1875 (loop for v being the hash-values of ht do
(print v
))
1876 (loop for k being the hash-keys of ht do
(print k
))
1877 (loop for v being the hash-values of ht using
(hash-key k
) do
(print (list k v
)))
1878 (loop for k being the hash-keys of ht using
(hash-value v
) do
(print (list k v
)))
1881 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
&key which
)
1882 (check-type which
(member hash-key hash-value
))
1883 (cond ((or (cdr prep-phrases
) (not (member (caar prep-phrases
) '(:in
:of
))))
1884 (loop-error "Too many prepositions!"))
1885 ((null prep-phrases
) (loop-error "Missing OF or IN in ~S iteration path.")))
1886 (let ((ht-var (loop-gentemp 'loop-hashtab-
))
1887 (next-fn (loop-gentemp 'loop-hashtab-next-
))
1888 (dummy-predicate-var nil
)
1890 (multiple-value-bind (other-var other-p
)
1891 (named-variable (if (eq which
'hash-key
) 'hash-value
'hash-key
))
1892 ;;@@@@ named-variable returns a second value of T if the name was actually
1893 ;; specified, so clever code can throw away the gensym'ed up variable if
1894 ;; it isn't really needed.
1895 ;;The following is for those implementations in which we cannot put dummy NILs
1896 ;; into multiple-value-setq variable lists.
1897 #-Genera
(setq other-p t
1898 dummy-predicate-var
(loop-when-it-variable))
1902 (bindings `((,variable nil
,data-type
)
1903 (,ht-var
,(cadar prep-phrases
))
1904 ,@(and other-p other-var
`((,other-var nil
))))))
1907 (setq key-var variable val-var
(and other-p other-var
))
1909 (pushnew val-var ignore-vars
)))
1910 (hash-value ; default?
1911 (setq key-var
(and other-p other-var
) val-var variable
)
1913 (pushnew key-var ignore-vars
))))
1914 (push `(with-hash-table-iterator (,next-fn
,ht-var
)) *loop-wrappers
*)
1915 (when (consp key-var
)
1916 (setq post-steps
`(,key-var
,(setq key-var
(loop-gentemp 'loop-hash-key-temp-
))
1918 (push `(,key-var nil
) bindings
))
1919 (when (consp val-var
)
1920 (setq post-steps
`(,val-var
,(setq val-var
(loop-gentemp 'loop-hash-val-temp-
))
1922 (push `(,val-var nil
) bindings
))
1923 (pushnew dummy-predicate-var ignore-vars
)
1925 (pushnew `(ignorable ,@ignore-vars
)
1928 `(,bindings
;bindings
1932 (not (multiple-value-setq (,dummy-predicate-var
,key-var
,val-var
) (,next-fn
))) ;post-test
1936 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
&key symbol-types
)
1937 (cond ((or (cdr prep-phrases
) (not (member (caar prep-phrases
) '(:in
:of
))))
1938 (loop-error "Too many prepositions!"))
1939 ((null prep-phrases
) (loop-error "Missing OF or IN in ~S iteration path.")))
1940 (unless (symbolp variable
)
1941 (loop-error "Destructuring is not valid for package symbol iteration."))
1942 (let ((pkg-var (loop-gentemp 'loop-pkgsym-
))
1943 (next-fn (loop-gentemp 'loop-pkgsym-next-
)))
1944 (push `(with-package-iterator (,next-fn
,pkg-var
,@symbol-types
)) *loop-wrappers
*)
1945 `(((,variable nil
,data-type
) (,pkg-var
,(cadar prep-phrases
)))
1949 (not (multiple-value-setq (,(progn
1950 ;;@@@@ If an implementation can get away without actually
1951 ;; using a variable here, so much the better.
1953 #-Genera
(loop-when-it-variable))
1961 (defun make-ansi-loop-universe (extended-p)
1962 (let ((w (make-standard-loop-universe
1963 :keywords
`((named (loop-do-named))
1964 (initially (loop-do-initially))
1965 (finally (loop-do-finally))
1967 (doing (loop-do-do))
1968 (return (loop-do-return))
1969 (collect (loop-list-collection list
))
1970 (collecting (loop-list-collection list
))
1971 (append (loop-list-collection append
))
1972 (appending (loop-list-collection append
))
1973 (nconc (loop-list-collection nconc
))
1974 (nconcing (loop-list-collection nconc
))
1975 (count (loop-sum-collection count
,*loop-real-data-type
* fixnum
))
1976 (counting (loop-sum-collection count
,*loop-real-data-type
* fixnum
))
1977 (sum (loop-sum-collection sum number number
))
1978 (summing (loop-sum-collection sum number number
))
1979 (maximize (loop-maxmin-collection max
))
1980 (minimize (loop-maxmin-collection min
))
1981 (maximizing (loop-maxmin-collection max
))
1982 (minimizing (loop-maxmin-collection min
))
1983 (always (loop-do-always t nil
)) ; Normal, do always
1984 (never (loop-do-always t t
)) ; Negate the test on always.
1985 (thereis (loop-do-thereis t
))
1986 (while (loop-do-while nil
:while
)) ; Normal, do while
1987 (until (loop-do-while t
:until
)) ; Negate the test on while
1988 (when (loop-do-if when nil
)) ; Normal, do when
1989 (if (loop-do-if if nil
)) ; synonymous
1990 (unless (loop-do-if unless t
)) ; Negate the test on when
1991 (with (loop-do-with)))
1992 :for-keywords
'((= (loop-ansi-for-equals))
1993 (across (loop-for-across))
1996 (from (loop-for-arithmetic :from
))
1997 (downfrom (loop-for-arithmetic :downfrom
))
1998 (upfrom (loop-for-arithmetic :upfrom
))
1999 (below (loop-for-arithmetic :below
))
2000 (to (loop-for-arithmetic :to
))
2001 (upto (loop-for-arithmetic :upto
))
2002 (being (loop-for-being)))
2003 :iteration-keywords
'((for (loop-do-for))
2005 (repeat (loop-do-repeat)))
2006 :type-symbols
'(array atom bignum bit bit-vector character compiled-function
2007 complex cons double-float fixnum float
2008 function hash-table integer keyword list long-float
2009 nil null number package pathname random-state
2010 ratio rational readtable sequence short-float
2011 simple-array simple-bit-vector simple-string
2012 simple-vector single-float standard-char
2013 stream string base-char
2016 :ansi
(if extended-p
:extended t
))))
2017 (add-loop-path '(hash-key hash-keys
) 'loop-hash-table-iteration-path w
2018 :preposition-groups
'((:of
:in
))
2019 :inclusive-permitted nil
2020 :user-data
'(:which hash-key
))
2021 (add-loop-path '(hash-value hash-values
) 'loop-hash-table-iteration-path w
2022 :preposition-groups
'((:of
:in
))
2023 :inclusive-permitted nil
2024 :user-data
'(:which hash-value
))
2025 (add-loop-path '(symbol symbols
) 'loop-package-symbols-iteration-path w
2026 :preposition-groups
'((:of
:in
))
2027 :inclusive-permitted nil
2028 :user-data
'(:symbol-types
(:internal
:external
:inherited
)))
2029 (add-loop-path '(external-symbol external-symbols
) 'loop-package-symbols-iteration-path w
2030 :preposition-groups
'((:of
:in
))
2031 :inclusive-permitted nil
2032 :user-data
'(:symbol-types
(:external
)))
2033 (add-loop-path '(present-symbol present-symbols
) 'loop-package-symbols-iteration-path w
2034 :preposition-groups
'((:of
:in
))
2035 :inclusive-permitted nil
2036 :user-data
'(:symbol-types
(:internal
)))
2040 (defparameter *loop-ansi-universe
*
2041 (make-ansi-loop-universe nil
))
2044 (defun loop-standard-expansion (keywords-and-forms environment universe
)
2045 (if (and keywords-and-forms
(symbolp (car keywords-and-forms
)))
2046 (loop-translate keywords-and-forms environment universe
)
2047 (let ((tag (gensym)))
2048 `(block nil
(tagbody ,tag
(progn ,@keywords-and-forms
) (go ,tag
))))))
2053 (defmacro loop
(&rest keywords-and-forms
)
2054 #+Genera
(declare (compiler:do-not-record-macroexpansions
)
2055 (zwei:indentation . zwei
:indent-loop
))
2056 (loop-standard-expansion keywords-and-forms nil
*loop-ansi-universe
*))
2058 ;;;INTERFACE: Traditional, ANSI, Lucid.
2059 (defmacro loop-finish
()
2060 "Causes the iteration to terminate \"normally\", the same as implicit
2061 termination by an iteration driving clause, or by use of WHILE or
2062 UNTIL -- the epilogue code (if any) will be run, and any implicitly
2063 collected result will be returned as the value of the LOOP."
2067 (defmacro loop-body
(prologue
2072 &aux
(env nil
) rbefore rafter flagvar
)
2073 (unless (= (length before-loop
) (length after-loop
))
2074 (error "LOOP-BODY called with non-synched before- and after-loop lists."))
2075 ;;All our work is done from these copies, working backwards from the end:
2076 (setq rbefore
(reverse before-loop
) rafter
(reverse after-loop
))
2082 (when (and (consp x
) (member (car x
) '(go return return-from
)))
2085 (pify (l) (if (null (cdr l
)) (car l
) `(progn ,@l
)))
2087 (let ((form `(tagbody
2088 ,@(psimp (append prologue
(nreverse rbefore
)))
2090 ,@(psimp (append main-body
(nreconc rafter
`((go next-loop
)))))
2092 ,@(psimp epilogue
))))
2093 (if flagvar
`(let ((,flagvar nil
)) ,form
) form
))))
2094 (when (or *loop-duplicate-code
* (not rbefore
))
2095 (return-from loop-body
(makebody)))
2096 ;; This outer loop iterates once for each not-first-time flag test generated
2097 ;; plus once more for the forms that don't need a flag test
2098 (do ((threshold (loop-code-duplication-threshold env
))) (nil)
2099 (declare (fixnum threshold
))
2100 ;; Go backwards from the ends of before-loop and after-loop merging all the equivalent
2101 ;; forms into the body.
2102 (do () ((or (null rbefore
) (not (equal (car rbefore
) (car rafter
)))))
2103 (push (pop rbefore
) main-body
)
2105 (unless rbefore
(return (makebody)))
2106 ;; The first forms in rbefore & rafter (which are the chronologically
2107 ;; last forms in the list) differ, therefore they cannot be moved
2108 ;; into the main body. If everything that chronologically precedes
2109 ;; them either differs or is equal but is okay to duplicate, we can
2110 ;; just put all of rbefore in the prologue and all of rafter after
2111 ;; the body. Otherwise, there is something that is not okay to
2112 ;; duplicate, so it and everything chronologically after it in
2113 ;; rbefore and rafter must go into the body, with a flag test to
2114 ;; distinguish the first time around the loop from later times.
2115 ;; What chronologically precedes the non-duplicatable form will
2116 ;; be handled the next time around the outer loop.
2117 (do ((bb rbefore
(cdr bb
)) (aa rafter
(cdr aa
)) (lastdiff nil
) (count 0) (inc nil
))
2118 ((null bb
) (return-from loop-body
(makebody))) ;Did it.
2119 (cond ((not (equal (car bb
) (car aa
))) (setq lastdiff bb count
0))
2120 ((or (not (setq inc
(estimate-code-size (car bb
) env
)))
2121 (> (incf count inc
) threshold
))
2122 ;; Ok, we have found a non-duplicatable piece of code. Everything
2123 ;; chronologically after it must be in the central body.
2124 ;; Everything chronologically at and after lastdiff goes into the
2125 ;; central body under a flag test.
2126 (let ((then nil
) (else nil
))
2128 (push (pop rbefore
) else
)
2129 (push (pop rafter
) then
)
2130 (when (eq rbefore
(cdr lastdiff
)) (return)))
2132 (push `(setq ,(setq flagvar
*loop-iteration-flag-variable
*) t
) else
))
2133 (push `(if ,flagvar
,(pify (psimp then
)) ,(pify (psimp else
)))
2135 ;; Everything chronologically before lastdiff until the non-duplicatable form (car bb)
2136 ;; is the same in rbefore and rafter so just copy it into the body
2139 (push (pop rbefore
) main-body
)
2140 (when (eq rbefore
(cdr bb
)) (return)))
2144 (defmacro loop-really-desetq
(&rest var-val-pairs
&aux
(env nil
))
2145 (labels ((find-non-null (var)
2146 ;; see if there's any non-null thing here
2147 ;; recurse if the list element is itself a list
2148 (do ((tail var
)) ((not (consp tail
)) tail
)
2149 (when (find-non-null (pop tail
)) (return t
))))
2150 (loop-desetq-internal (var val
&optional temp
)
2151 ;; returns a list of actions to be performed
2155 ;; don't lose possible side-effects
2156 (if (eq (car val
) 'prog1
)
2157 ;; these can come from psetq or desetq below.
2158 ;; throw away the value, keep the side-effects.
2159 ;;Special case is for handling an expanded POP.
2160 (mapcan #'(lambda (x)
2162 (or (not (eq (car x
) 'car
))
2163 (not (symbolp (cadr x
)))
2164 (not (symbolp (setq x
(movitz::movitz-macroexpand x env
)))))
2169 (let* ((car (car var
))
2171 (car-non-null (find-non-null car
))
2172 (cdr-non-null (find-non-null cdr
)))
2173 (when (or car-non-null cdr-non-null
)
2175 (let* ((temp-p temp
)
2176 (temp (or temp
*loop-desetq-temporary
*))
2177 (body #+LOOP-Prefer-POP
`(,@(loop-desetq-internal
2180 (setq ,temp
(cdr ,temp
))))
2181 ,@(loop-desetq-internal cdr temp temp
))
2182 #-LOOP-Prefer-POP
`(,@(loop-desetq-internal car
`(car ,temp
))
2183 (setq ,temp
(cdr ,temp
))
2184 ,@(loop-desetq-internal cdr temp temp
))))
2186 `(,@(unless (eq temp val
)
2187 `((setq ,temp
,val
)))
2189 `((let ((,temp
,val
))
2192 (loop-desetq-internal car
`(car ,val
) temp
)))))
2194 (unless (eq var val
)
2195 `((setq ,var
,val
)))))))
2197 ((null var-val-pairs
)
2198 (if (null (cdr actions
)) (car actions
) `(progn ,@(nreverse actions
))))
2199 (setq actions
(revappend
2200 (loop-desetq-internal (pop var-val-pairs
) (pop var-val-pairs
))
2204 (defun excl::complex-loop-expander
(body env
)
2205 (loop-standard-expansion body env
*loop-ansi-universe
*))