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