Remove list of atomic types specs in 'loop'
[sbcl.git] / src / code / loop.lisp
blobdb84b94ef1a9dca53042ec4d3df83aee4cfa35b3
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!xc:defmacro 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!xc:defmacro 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!xc:defmacro 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!xc:defmacro 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!xc:defmacro 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!xc:defmacro loop-store-table-data (symbol table datum)
268 `(setf (gethash (symbol-name ,symbol) ,table) ,datum))
270 (defstruct (loop-universe
271 (:constructor !make-loop-universe)
272 (:copier nil)
273 (:predicate nil))
274 keywords ; hash table, value = (fn-name . extra-data)
275 iteration-keywords ; hash table, value = (fn-name . extra-data)
276 for-keywords ; hash table, value = (fn-name . extra-data)
277 path-keywords ; hash table, value = (fn-name . extra-data)
278 type-symbols ; hash table of type SYMBOLS, test EQ,
279 ; value = CL type specifier
280 type-keywords) ; hash table of type STRINGS, test EQUAL,
281 ; value = CL type spec
282 (sb!int:def!method print-object ((u loop-universe) stream)
283 (print-unreadable-object (u stream :type t :identity t)))
285 ;;; This is the "current" loop context in use when we are expanding a
286 ;;; loop. It gets bound on each invocation of LOOP.
287 (defvar *loop-universe*)
289 (defun !make-standard-loop-universe (&key keywords for-keywords
290 iteration-keywords path-keywords
291 type-keywords type-symbols)
292 (flet ((maketable (entries)
293 (let* ((size (length entries))
294 (ht (make-hash-table :size (if (< size 10) 10 size)
295 :test 'equal)))
296 (dolist (x entries)
297 (setf (gethash (symbol-name (car x)) ht) (cadr x)))
298 ht)))
299 (!make-loop-universe
300 :keywords (maketable keywords)
301 :for-keywords (maketable for-keywords)
302 :iteration-keywords (maketable iteration-keywords)
303 :path-keywords (maketable path-keywords)
304 :type-keywords (maketable type-keywords)
305 :type-symbols (let* ((size (length type-symbols))
306 (ht (make-hash-table :size (if (< size 10) 10 size)
307 :test 'eq)))
308 (dolist (x type-symbols)
309 (if (atom x)
310 (setf (gethash x ht) x)
311 (setf (gethash (car x) ht) (cadr x))))
312 ht))))
314 ;;;; SETQ hackery, including destructuring ("DESETQ")
316 (defun loop-make-psetq (frobs)
317 (and frobs
318 (loop-make-desetq
319 (list (car frobs)
320 (if (null (cddr frobs)) (cadr frobs)
321 `(prog1 ,(cadr frobs)
322 ,(loop-make-psetq (cddr frobs))))))))
324 (defun loop-make-desetq (var-val-pairs)
325 (if (null var-val-pairs)
327 (cons 'loop-really-desetq var-val-pairs)))
329 (defvar *loop-desetq-temporary*
330 (make-symbol "LOOP-DESETQ-TEMP"))
332 (sb!xc:defmacro loop-really-desetq (&environment env
333 &rest var-val-pairs)
334 (labels ((find-non-null (var)
335 ;; See whether there's any non-null thing here. Recurse
336 ;; if the list element is itself a list.
337 (do ((tail var)) ((not (consp tail)) tail)
338 (when (find-non-null (pop tail)) (return t))))
339 (loop-desetq-internal (var val &optional temp)
340 ;; returns a list of actions to be performed
341 (typecase var
342 (null
343 (when (consp val)
344 ;; Don't lose possible side effects.
345 (if (eq (car val) 'prog1)
346 ;; These can come from PSETQ or DESETQ below.
347 ;; Throw away the value, keep the side effects.
348 ;; Special case is for handling an expanded POP.
349 (mapcan (lambda (x)
350 (and (consp x)
351 (or (not (eq (car x) 'car))
352 (not (symbolp (cadr x)))
353 (not (symbolp (setq x (sb!int:%macroexpand x env)))))
354 (cons x nil)))
355 (cdr val))
356 `(,val))))
357 (cons
358 (let* ((car (car var))
359 (cdr (cdr var))
360 (car-non-null (find-non-null car))
361 (cdr-non-null (find-non-null cdr)))
362 (when (or car-non-null cdr-non-null)
363 (if cdr-non-null
364 (let* ((temp-p temp)
365 (temp (or temp *loop-desetq-temporary*))
366 (body `(,@(loop-desetq-internal car
367 `(car ,temp))
368 (setq ,temp (cdr ,temp))
369 ,@(loop-desetq-internal cdr
370 temp
371 temp))))
372 (if temp-p
373 `(,@(unless (eq temp val)
374 `((setq ,temp ,val)))
375 ,@body)
376 `((let ((,temp ,val))
377 ,@body))))
378 ;; no CDRing to do
379 (loop-desetq-internal car `(car ,val) temp)))))
380 (otherwise
381 (unless (eq var val)
382 `((setq ,var ,val)))))))
383 (do ((actions))
384 ((null var-val-pairs)
385 (if (null (cdr actions)) (car actions) `(progn ,@(nreverse actions))))
386 (setq actions (revappend
387 (loop-desetq-internal (pop var-val-pairs)
388 (pop var-val-pairs))
389 actions)))))
391 ;;;; LOOP-local variables
393 ;;; This is the "current" pointer into the LOOP source code.
394 (defvar *loop-source-code*)
396 ;;; This is the pointer to the original, for things like NAMED that
397 ;;; insist on being in a particular position
398 (defvar *loop-original-source-code*)
400 ;;; This is *loop-source-code* as of the "last" clause. It is used
401 ;;; primarily for generating error messages (see loop-error, loop-warn).
402 (defvar *loop-source-context*)
404 ;;; list of names for the LOOP, supplied by the NAMED clause
405 (defvar *loop-names*)
407 ;;; The macroexpansion environment given to the macro.
408 (defvar *loop-macro-environment*)
410 ;;; This holds variable names specified with the USING clause.
411 ;;; See LOOP-NAMED-VAR.
412 (defvar *loop-named-vars*)
414 ;;; LETlist-like list being accumulated for current group of bindings.
415 (defvar *loop-vars*)
417 ;;; List of declarations being accumulated in parallel with
418 ;;; *LOOP-VARS*.
419 (defvar *loop-declarations*)
421 ;;; Declarations for destructuring bindings
422 (defvar *loop-desetq-declarations*)
424 ;;; This is used by LOOP for destructuring binding, if it is doing
425 ;;; that itself. See LOOP-MAKE-VAR.
426 (defvar *loop-desetq*)
428 ;;; list of wrapping forms, innermost first, which go immediately
429 ;;; inside the current set of parallel bindings being accumulated in
430 ;;; *LOOP-VARS*. The wrappers are appended onto a body. E.g., this
431 ;;; list could conceivably have as its value
432 ;;; ((WITH-OPEN-FILE (G0001 G0002 ...))),
433 ;;; with G0002 being one of the bindings in *LOOP-VARS* (This is why
434 ;;; the wrappers go inside of the variable bindings).
435 (defvar *loop-wrappers*)
437 ;;; This accumulates lists of previous values of *LOOP-VARS* and the
438 ;;; other lists above, for each new nesting of bindings. See
439 ;;; LOOP-BIND-BLOCK.
440 (defvar *loop-bind-stack*)
442 ;;; list of prologue forms of the loop, accumulated in reverse order
443 (defvar *loop-prologue*)
445 (defvar *loop-before-loop*)
446 (defvar *loop-body*)
447 (defvar *loop-after-body*)
449 ;;; This is T if we have emitted any body code, so that iteration
450 ;;; driving clauses can be disallowed. This is not strictly the same
451 ;;; as checking *LOOP-BODY*, because we permit some clauses such as
452 ;;; RETURN to not be considered "real" body (so as to permit the user
453 ;;; to "code" an abnormal return value "in loop").
454 (defvar *loop-emitted-body*)
456 ;;; list of epilogue forms (supplied by FINALLY generally), accumulated
457 ;;; in reverse order
458 (defvar *loop-epilogue*)
460 ;;; list of epilogue forms which are supplied after the above "user"
461 ;;; epilogue. "Normal" termination return values are provide by
462 ;;; putting the return form in here. Normally this is done using
463 ;;; LOOP-EMIT-FINAL-VALUE, q.v.
464 (defvar *loop-after-epilogue*)
466 ;;; the "culprit" responsible for supplying a final value from the
467 ;;; loop. This is so LOOP-DISALLOW-AGGREGATE-BOOLEANS can moan about
468 ;;; disallowed anonymous collections.
469 (defvar *loop-final-value-culprit*)
471 ;;; If this is true, we are in some branch of a conditional. Some
472 ;;; clauses may be disallowed.
473 (defvar *loop-inside-conditional*)
475 ;;; If not NIL, this is a temporary bound around the loop for holding
476 ;;; the temporary value for "it" in things like "when (f) collect it".
477 ;;; It may be used as a supertemporary by some other things.
478 (defvar *loop-when-it-var*)
480 ;;; Sometimes we decide we need to fold together parts of the loop,
481 ;;; but some part of the generated iteration code is different for the
482 ;;; first and remaining iterations. This variable will be the
483 ;;; temporary which is the flag used in the loop to tell whether we
484 ;;; are in the first or remaining iterations.
485 (defvar *loop-never-stepped-var*)
487 ;;; list of all the value-accumulation descriptor structures in the
488 ;;; loop. See LOOP-GET-COLLECTION-INFO.
489 (defvar *loop-collection-cruft*) ; for multiple COLLECTs (etc.)
491 ;;;; code analysis stuff
493 (defun loop-constant-fold-if-possible (form &optional expected-type)
494 (let* ((constantp (sb!xc:constantp form))
495 (value (and constantp (sb!int:constant-form-value form))))
496 (when (and constantp expected-type)
497 (unless (sb!xc:typep value expected-type)
498 (loop-warn "~@<The form ~S evaluated to ~S, which was not of ~
499 the anticipated type ~S.~:@>"
500 form value expected-type)
501 (setq constantp nil value nil)))
502 (values form constantp value)))
504 (sb!xc:defmacro loop-body (prologue
505 before-loop
506 main-body
507 after-loop
508 epilogue)
509 (unless (= (length before-loop) (length after-loop))
510 (error "LOOP-BODY called with non-synched before- and after-loop lists"))
511 ;; All our work is done from these copies, working backwards from the end
512 (let ((rbefore (reverse before-loop))
513 (rafter (reverse after-loop)))
514 ;; Go backwards from the ends of before-loop and after-loop
515 ;; merging all the equivalent forms into the body.
516 (do ()
517 ((or (null rbefore)
518 (not (equal (car rbefore) (car rafter)))))
519 (push (pop rbefore) main-body)
520 (pop rafter))
521 `(tagbody
522 ,@(remove nil prologue)
523 ,@(nreverse (remove nil rbefore))
524 next-loop
525 ,@(remove nil main-body)
526 ,@(nreverse (remove nil rafter))
527 (go next-loop)
528 end-loop
529 ,@(remove nil epilogue))))
531 ;;;; loop errors
533 (defun loop-context ()
534 (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
535 ((eq l (cdr *loop-source-code*)) (nreverse new))))
537 (defun loop-error (format-string &rest format-args)
538 (error 'sb!int:simple-program-error
539 :format-control "~?~%current LOOP context:~{ ~S~}."
540 :format-arguments (list format-string format-args (loop-context))))
542 (defun loop-warn (format-string &rest format-args)
543 (warn "~?~%current LOOP context:~{ ~S~}."
544 format-string
545 format-args
546 (loop-context)))
548 (defun loop-check-data-type (specified-type required-type
549 &optional (default-type required-type))
550 (if (null specified-type)
551 default-type
552 (multiple-value-bind (a b) (sb!xc:subtypep specified-type required-type)
553 (cond ((not b)
554 (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
555 specified-type required-type))
556 ((not a)
557 (loop-error "The specified data type ~S is not a subtype of ~S."
558 specified-type required-type)))
559 specified-type)))
561 ;;; Transform the LOOP kind of destructuring into the DESTRUCTURING-BIND kind
562 ;;; basically by adding &optional and ignored &rest dotted list
563 (defun transform-destructuring (tree)
564 (let (ignores)
565 (labels ((transform (tree)
566 (do ((result (list '&optional))
567 (cdr tree (cdr cdr)))
568 (())
569 (cond ((null cdr)
570 (return (nreconc result
571 (car (push (gensym "LOOP-IGNORED-")
572 ignores)))))
573 ((atom cdr)
574 (return (nreconc result cdr)))
575 ((consp (car cdr))
576 (push (list (transform (car cdr))) result))
577 ((null (car cdr))
578 (push (car (push (gensym "LOOP-IGNORED-")
579 ignores))
580 result))
582 (push (car cdr) result))))))
583 (values (transform tree) ignores))))
585 (sb!xc:defmacro loop-destructuring-bind
586 (lambda-list args &rest body)
587 (multiple-value-bind (d-lambda-list ignores)
588 (transform-destructuring lambda-list)
589 `(destructuring-bind ,d-lambda-list ,args
590 (declare (ignore ,@ignores))
591 ,@body)))
593 (defun loop-build-destructuring-bindings (crocks forms)
594 (if crocks
595 `((loop-destructuring-bind ,(car crocks) ,(cadr crocks)
596 ,@(loop-build-destructuring-bindings (cddr crocks) forms)))
597 forms))
599 (defun loop-translate (*loop-source-code*
600 *loop-macro-environment*
601 *loop-universe*)
602 (let ((*loop-original-source-code* *loop-source-code*)
603 (*loop-source-context* nil)
604 (*loop-vars* nil)
605 (*loop-named-vars* nil)
606 (*loop-declarations* nil)
607 (*loop-desetq-declarations* nil)
608 (*loop-desetq* nil)
609 (*loop-bind-stack* nil)
610 (*loop-prologue* nil)
611 (*loop-wrappers* nil)
612 (*loop-before-loop* nil)
613 (*loop-body* nil)
614 (*loop-emitted-body* nil)
615 (*loop-after-body* nil)
616 (*loop-epilogue* nil)
617 (*loop-after-epilogue* nil)
618 (*loop-final-value-culprit* nil)
619 (*loop-inside-conditional* nil)
620 (*loop-when-it-var* nil)
621 (*loop-never-stepped-var* nil)
622 (*loop-names* nil)
623 (*loop-collection-cruft* nil))
624 (loop-iteration-driver)
625 (loop-bind-block)
626 (let ((answer `(loop-body
627 ,(nreverse *loop-prologue*)
628 ,(nreverse *loop-before-loop*)
629 ,(nreverse *loop-body*)
630 ,(nreverse *loop-after-body*)
631 ,(nreconc *loop-epilogue*
632 (nreverse *loop-after-epilogue*)))))
633 (dolist (entry *loop-bind-stack*)
634 (destructuring-bind (vars dcls desetq desetq-decls wrappers) entry
635 (dolist (w wrappers)
636 (setq answer (append w (list answer))))
637 (when (or vars dcls desetq)
638 (let ((forms (list answer)))
639 (when desetq-decls
640 (push `(declare ,@desetq-decls) forms))
641 (setq answer `(,(if vars 'let 'locally)
642 ,vars
643 (declare ,@dcls)
644 ,@(loop-build-destructuring-bindings desetq
645 forms)))))))
646 (do () (nil)
647 (setq answer `(block ,(pop *loop-names*) ,answer))
648 (unless *loop-names* (return nil)))
649 answer)))
651 (defun loop-iteration-driver ()
652 (do ()
653 ((null *loop-source-code*))
654 (let ((keyword (car *loop-source-code*)) (tem nil))
655 (cond ((not (symbolp keyword))
656 (loop-error "~S found where LOOP keyword expected" keyword))
657 (t (setq *loop-source-context* *loop-source-code*)
658 (loop-pop-source)
659 (cond ((setq tem
660 (loop-lookup-keyword keyword
661 (loop-universe-keywords
662 *loop-universe*)))
663 ;; It's a "miscellaneous" toplevel LOOP keyword (DO,
664 ;; COLLECT, NAMED, etc.)
665 (apply (symbol-function (first tem)) (rest tem)))
666 ((setq tem
667 (loop-lookup-keyword keyword
668 (loop-universe-iteration-keywords *loop-universe*)))
669 (loop-hack-iteration tem))
670 ((loop-tmember keyword '(and else))
671 ;; The alternative is to ignore it, i.e. let it go
672 ;; around to the next keyword...
673 (loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
674 keyword
675 (car *loop-source-code*)
676 (cadr *loop-source-code*)))
677 (t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
679 (defun loop-pop-source ()
680 (if *loop-source-code*
681 (pop *loop-source-code*)
682 (loop-error "LOOP source code ran out when another token was expected.")))
684 (defun loop-get-form ()
685 (if *loop-source-code*
686 (loop-pop-source)
687 (loop-error "LOOP code ran out where a form was expected.")))
689 (defun loop-get-compound-form ()
690 (let ((form (loop-get-form)))
691 (unless (consp form)
692 (loop-error "A compound form was expected, but ~S found." form))
693 form))
695 (defun loop-get-progn ()
696 (do ((forms (list (loop-get-compound-form))
697 (cons (loop-get-compound-form) forms))
698 (nextform (car *loop-source-code*)
699 (car *loop-source-code*)))
700 ((atom nextform)
701 (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
703 (defun loop-construct-return (form)
704 `(return-from ,(car *loop-names*) ,form))
706 (defun loop-pseudo-body (form)
707 (cond ((or *loop-emitted-body* *loop-inside-conditional*)
708 (push form *loop-body*))
709 (t (push form *loop-before-loop*) (push form *loop-after-body*))))
711 (defun loop-emit-body (form)
712 (setq *loop-emitted-body* t)
713 (loop-pseudo-body form))
715 (defun loop-emit-final-value (&optional (form nil form-supplied-p))
716 (when form-supplied-p
717 (push (loop-construct-return form) *loop-after-epilogue*))
718 (setq *loop-final-value-culprit* (car *loop-source-context*)))
720 (defun loop-disallow-conditional (&optional kwd)
721 (when *loop-inside-conditional*
722 (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
724 (defun loop-disallow-anonymous-collectors ()
725 (when (find-if-not 'loop-collector-name *loop-collection-cruft*)
726 (loop-error "This LOOP clause is not permitted with anonymous collectors.")))
728 (defun loop-disallow-aggregate-booleans ()
729 (when (loop-tmember *loop-final-value-culprit* '(always never thereis))
730 (loop-error "This anonymous collection LOOP clause is not permitted with aggregate booleans.")))
732 ;;;; loop types
734 (defun loop-typed-init (data-type &optional step-var-p)
735 ;; FIXME: can't tell if unsupplied or NIL, but it has to be rare.
736 (when data-type
737 (let ((ctype (sb!kernel:specifier-type data-type)))
738 ;; FIXME: use the ctype for the rest of the type operations, now
739 ;; that it's parsed.
740 (cond ((eql ctype sb!kernel:*empty-type*)
741 (values nil t))
742 ((sb!xc:subtypep data-type 'number)
743 (let ((init (if step-var-p 1 0)))
744 (flet ((like (&rest types)
745 (coerce init (find-if (lambda (type)
746 (sb!xc:subtypep data-type type))
747 types))))
748 (cond ((sb!xc:subtypep data-type 'float)
749 (like 'single-float 'double-float
750 'short-float 'long-float 'float))
751 ((sb!xc:subtypep data-type '(complex float))
752 (like '(complex single-float)
753 '(complex double-float)
754 '(complex short-float)
755 '(complex long-float)
756 '(complex float)))
758 init)))))
759 ((sb!xc:subtypep data-type 'vector)
760 (when (sb!kernel:array-type-p ctype)
761 (let ((etype (sb!kernel:type-*-to-t
762 (sb!kernel:array-type-specialized-element-type ctype))))
763 (make-array 0 :element-type (sb!kernel:type-specifier etype)))))
764 #!+sb-unicode
765 ((sb!xc:subtypep data-type 'extended-char)
766 (code-char sb!int:base-char-code-limit))
767 ((sb!xc:subtypep data-type 'character)
768 #\x)
770 nil)))))
772 (defun loop-optional-type (&optional variable)
773 ;; No variable specified implies that no destructuring is permissible.
774 (and *loop-source-code* ; Don't get confused by NILs..
775 (let ((z (car *loop-source-code*)))
776 (cond ((loop-tequal z 'of-type)
777 ;; This is the syntactically unambigous form in that
778 ;; the form of the type specifier does not matter.
779 ;; Also, it is assumed that the type specifier is
780 ;; unambiguously, and without need of translation, a
781 ;; common lisp type specifier or pattern (matching the
782 ;; variable) thereof.
783 (loop-pop-source)
784 (loop-pop-source))
786 ((symbolp z)
787 ;; This is the (sort of) "old" syntax, even though we
788 ;; didn't used to support all of these type symbols.
789 (let ((type-spec (or (gethash z
790 (loop-universe-type-symbols
791 *loop-universe*))
792 (gethash (symbol-name z)
793 (loop-universe-type-keywords
794 *loop-universe*)))))
795 (when type-spec
796 (loop-pop-source)
797 type-spec)))
799 ;; This is our sort-of old syntax. But this is only
800 ;; valid for when we are destructuring, so we will be
801 ;; compulsive (should we really be?) and require that
802 ;; we in fact be doing variable destructuring here. We
803 ;; must translate the old keyword pattern typespec
804 ;; into a fully-specified pattern of real type
805 ;; specifiers here.
806 (if (consp variable)
807 (unless (consp z)
808 (loop-error
809 "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
811 (loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
812 (loop-pop-source)
813 (labels ((translate (k v)
814 (cond ((null k) nil)
815 ((atom k)
816 (replicate
817 (or (gethash k
818 (loop-universe-type-symbols
819 *loop-universe*))
820 (gethash (symbol-name k)
821 (loop-universe-type-keywords
822 *loop-universe*))
823 (loop-error
824 "The destructuring type pattern ~S contains the unrecognized type keyword ~S."
825 z k))
827 ((atom v)
828 (loop-error
829 "The destructuring type pattern ~S doesn't match the variable pattern ~S."
830 z variable))
831 (t (cons (translate (car k) (car v))
832 (translate (cdr k) (cdr v))))))
833 (replicate (typ v)
834 (if (atom v)
836 (cons (replicate typ (car v))
837 (replicate typ (cdr v))))))
838 (translate z variable)))))))
840 ;;;; loop variables
842 (defun loop-bind-block ()
843 (when (or *loop-vars* *loop-declarations* *loop-wrappers*
844 *loop-desetq*)
845 (push (list (nreverse *loop-vars*)
846 *loop-declarations*
847 *loop-desetq*
848 *loop-desetq-declarations*
849 *loop-wrappers*)
850 *loop-bind-stack*)
851 (setq *loop-vars* nil
852 *loop-declarations* nil
853 *loop-desetq* nil
854 *loop-desetq-declarations* nil
855 *loop-wrappers* nil)))
857 (defun check-var-name (name &optional (context ""))
858 (labels ((map-name (function name)
859 (do ((x (pop name) (pop name)))
860 (())
861 (typecase x
862 (null)
863 (cons (map-name function x))
864 (symbol (funcall function x))
866 (loop-error "Bad variable ~s~a" x context)))
867 (typecase name
868 (cons)
869 (null
870 (return))
871 (symbol
872 (funcall function name)
873 (return))
875 (loop-error "Bad variable ~s~a" name context)))))
876 (duplicate (x)
877 (loop-error "Duplicated variable ~s~a" x context))
878 (find-in-desetq (name desetqs)
879 (do* ((desetq desetqs (cddr desetq))
880 (var (car desetq) (car desetq)))
881 ((null desetq))
882 (map-name (lambda (x)
883 (when (eql name x)
884 (duplicate name)))
885 var))))
886 (cond ((consp name)
887 (map-name (lambda (x) (check-var-name x context)) name))
888 ((assoc name *loop-vars*)
889 (duplicate name))
890 ((find-in-desetq name *loop-desetq*))
892 (do ((entry *loop-bind-stack* (cdr entry)))
893 (nil)
894 (cond
895 ((null entry) (return nil))
896 ((assoc name (caar entry) :test #'eq)
897 (duplicate name))
899 (find-in-desetq name (caddar entry)))))))))
901 (defun loop-make-var (name initialization dtype &optional step-var-p)
902 (cond ((null name)
903 (setq name (gensym "LOOP-IGNORE-"))
904 (push (list name (or initialization (loop-typed-init dtype step-var-p)))
905 *loop-vars*)
906 (push `(ignore ,name) *loop-declarations*)
907 (loop-declare-var name dtype))
908 ((atom name)
909 (check-var-name name)
910 (loop-declare-var name dtype :step-var-p step-var-p
911 :initialization initialization)
912 ;; We use ASSOC on this list to check for duplications (above),
913 ;; so don't optimize out this list:
914 (push (list name (or initialization (loop-typed-init dtype step-var-p)))
915 *loop-vars*))
916 (initialization
917 (check-var-name name)
918 (let ((newvar (gensym "LOOP-DESTRUCTURE-")))
919 (loop-declare-var name dtype :desetq t)
920 (push (list newvar initialization) *loop-vars*)
921 ;; *LOOP-DESETQ* gathered in reverse order.
922 (setq *loop-desetq*
923 (list* name newvar *loop-desetq*))))
925 (let ((tcar nil) (tcdr nil))
926 (if (atom dtype) (setq tcar (setq tcdr dtype))
927 (setq tcar (car dtype) tcdr (cdr dtype)))
928 (loop-make-var (car name) nil tcar)
929 (when (cdr name)
930 (loop-make-var (cdr name) nil tcdr)))))
931 name)
933 ;;; Find a suitable type for default initialization
934 (defun type-for-default-init (type &optional step-var-p)
935 (multiple-value-bind (init empty-type)
936 (loop-typed-init type step-var-p)
937 (values
938 (cond (empty-type
939 ;; Don't wrap empty types `(or ...), otherwise the will no
940 ;; longer be empty and the compiler won't produce
941 ;; warnings.
942 type)
943 ((sb!xc:typep init type)
944 type)
945 ((sb!xc:typep init '(simple-array * (*)))
946 ;; type-of lets the size in
947 `(or (simple-array ,(array-element-type init) (*)) ,type))
949 `(or ,(sb!xc:type-of init) ,type)))
950 init)))
952 (defun loop-declare-var (name dtype &key step-var-p initialization
953 desetq)
954 (cond ((or (null name) (null dtype) (eq dtype t)) nil)
955 ((symbolp name)
956 (unless (or (sb!xc:subtypep t dtype)
957 (and (eq (find-package :cl) (symbol-package name))
958 (eq :special (sb!int:info :variable :kind name))))
959 (let ((dtype `(type ,(if initialization
960 dtype
961 (type-for-default-init dtype step-var-p))
962 ,name)))
963 (if desetq
964 (push dtype *loop-desetq-declarations*)
965 (push dtype *loop-declarations*)))))
966 ((consp name)
967 (cond ((consp dtype)
968 (loop-declare-var (car name) (car dtype)
969 :desetq desetq)
970 (loop-declare-var (cdr name) (cdr dtype)
971 :desetq desetq))
972 (t (loop-declare-var (car name) dtype
973 :desetq desetq)
974 (loop-declare-var (cdr name) dtype
975 :desetq desetq))))
976 (t (error "invalid LOOP variable passed in: ~S" name))))
978 (defun loop-maybe-bind-form (form data-type)
979 (if (constantp form)
980 form
981 (loop-make-var (gensym "LOOP-BIND-") form data-type)))
983 (defun loop-do-if (for negatep)
984 (let ((form (loop-get-form))
985 (*loop-inside-conditional* t)
986 (it-p nil)
987 (first-clause-p t))
988 (flet ((get-clause (for)
989 (do ((body nil)) (nil)
990 (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
991 (cond ((not (symbolp key))
992 (loop-error
993 "~S found where keyword expected getting LOOP clause after ~S"
994 key for))
995 (t (setq *loop-source-context* *loop-source-code*)
996 (loop-pop-source)
997 (when (and (loop-tequal (car *loop-source-code*) 'it)
998 first-clause-p)
999 (setq *loop-source-code*
1000 (cons (or it-p
1001 (setq it-p
1002 (loop-when-it-var)))
1003 (cdr *loop-source-code*))))
1004 (cond ((or (not (setq data (loop-lookup-keyword
1005 key (loop-universe-keywords *loop-universe*))))
1006 (progn (apply (symbol-function (car data))
1007 (cdr data))
1008 (null *loop-body*)))
1009 (loop-error
1010 "~S does not introduce a LOOP clause that can follow ~S."
1011 key for))
1012 (t (setq body (nreconc *loop-body* body)))))))
1013 (setq first-clause-p nil)
1014 (if (loop-tequal (car *loop-source-code*) :and)
1015 (loop-pop-source)
1016 (return (if (cdr body)
1017 `(progn ,@(nreverse body))
1018 (car body)))))))
1019 (let ((then (get-clause for))
1020 (else (when (loop-tequal (car *loop-source-code*) :else)
1021 (loop-pop-source)
1022 (list (get-clause :else)))))
1023 (when (loop-tequal (car *loop-source-code*) :end)
1024 (loop-pop-source))
1025 (when it-p (setq form `(setq ,it-p ,form)))
1026 (loop-pseudo-body
1027 `(if ,(if negatep `(not ,form) form)
1028 ,then
1029 ,@else))))))
1031 (defun loop-do-initially ()
1032 (loop-disallow-conditional :initially)
1033 (push (loop-get-progn) *loop-prologue*))
1035 (defun loop-do-finally ()
1036 (loop-disallow-conditional :finally)
1037 (push (loop-get-progn) *loop-epilogue*))
1039 (defun loop-do-do ()
1040 (loop-emit-body (loop-get-progn)))
1042 (defun loop-do-named ()
1043 (let ((name (loop-pop-source)))
1044 (unless (symbolp name)
1045 (loop-error "~S is an invalid name for your LOOP" name))
1046 (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1047 (loop-error "The NAMED ~S clause occurs too late." name))
1048 (when *loop-names*
1049 (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1050 (car *loop-names*) name))
1051 (setq *loop-names* (list name))))
1053 (defun loop-do-return ()
1054 (loop-emit-body (loop-construct-return (loop-get-form))))
1056 ;;;; value accumulation: LIST
1058 (defstruct (loop-collector
1059 (:copier nil)
1060 (:predicate nil))
1061 name
1062 class
1063 (history nil)
1064 (tempvars nil)
1065 specified-type
1066 dtype
1067 (data nil)) ;collector-specific data
1069 (sb!xc:defmacro with-sum-count (lc &body body)
1070 (let* ((type (loop-collector-dtype lc))
1071 (temp-var (car (loop-collector-tempvars lc))))
1072 (multiple-value-bind (type init)
1073 (type-for-default-init type)
1074 `(let ((,temp-var ,init))
1075 (declare (type ,type ,temp-var))
1076 ,@body))))
1078 (defun loop-get-collection-info (collector class default-type)
1079 (let ((form (loop-get-form))
1080 (name (when (loop-tequal (car *loop-source-code*) 'into)
1081 (loop-pop-source)
1082 (loop-pop-source))))
1083 (when (not (symbolp name))
1084 (loop-error "The value accumulation recipient name, ~S, is not a symbol." name))
1085 (unless name
1086 (loop-disallow-aggregate-booleans))
1087 (let* ((specified-type (loop-optional-type))
1088 (dtype (or specified-type default-type))
1089 (cruft (find (the symbol name) *loop-collection-cruft*
1090 :key #'loop-collector-name)))
1091 (cond ((not cruft)
1092 (check-var-name name " in INTO clause")
1093 (push (setq cruft (make-loop-collector
1094 :name name :class class
1095 :history (list collector)
1096 :specified-type specified-type
1097 :dtype dtype))
1098 *loop-collection-cruft*))
1099 (t (unless (eq (loop-collector-class cruft) class)
1100 (loop-error
1101 "incompatible kinds of LOOP value accumulation specified for collecting~@
1102 ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S"
1103 name (car (loop-collector-history cruft)) collector))
1104 (cond ((equal dtype (loop-collector-dtype cruft)))
1105 ((and (null specified-type)
1106 (null (loop-collector-specified-type cruft)))
1107 ;; Unionize types only for default types, most
1108 ;; likely, SUM and COUNT which have number and
1109 ;; fixnum respectively.
1110 (setf (loop-collector-dtype cruft)
1111 (sb!kernel:type-specifier
1112 (sb!kernel:type-union
1113 (sb!kernel:specifier-type dtype)
1114 (sb!kernel:specifier-type (loop-collector-dtype cruft))))))
1116 (loop-warn
1117 "unequal datatypes specified in different LOOP value accumulations~@
1118 into ~S: ~S and ~S"
1119 name dtype (loop-collector-dtype cruft))
1120 (when (eq (loop-collector-dtype cruft) t)
1121 (setf (loop-collector-dtype cruft) dtype))))
1122 (push collector (loop-collector-history cruft))))
1123 (values cruft form))))
1125 (defun loop-list-collection (specifically) ; NCONC, LIST, or APPEND
1126 (multiple-value-bind (lc form)
1127 (loop-get-collection-info specifically 'list 'list)
1128 (let ((tempvars (loop-collector-tempvars lc)))
1129 (unless tempvars
1130 (setf (loop-collector-tempvars lc)
1131 (setq tempvars (list* (gensym "LOOP-LIST-HEAD-")
1132 (gensym "LOOP-LIST-TAIL-")
1133 (and (loop-collector-name lc)
1134 (list (loop-collector-name lc))))))
1135 (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1136 (unless (loop-collector-name lc)
1137 (loop-emit-final-value `(loop-collect-answer ,(car tempvars)
1138 ,@(cddr tempvars)))))
1139 (ecase specifically
1140 (list (setq form `(list ,form)))
1141 (nconc nil)
1142 (append (unless (and (consp form) (eq (car form) 'list))
1143 (setq form `(copy-list ,form)))))
1144 (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1146 ;;;; value accumulation: MAX, MIN, SUM, COUNT
1148 (defun loop-sum-collection (specifically required-type default-type);SUM, COUNT
1149 (multiple-value-bind (lc form)
1150 (loop-get-collection-info specifically 'sum default-type)
1151 (loop-check-data-type (loop-collector-dtype lc) required-type)
1152 (let ((tempvars (loop-collector-tempvars lc)))
1153 (unless tempvars
1154 (setf (loop-collector-tempvars lc)
1155 (setq tempvars (list (or (loop-collector-name lc)
1156 (gensym "LOOP-SUM-")))))
1157 (unless (loop-collector-name lc)
1158 (loop-emit-final-value (car (loop-collector-tempvars lc))))
1159 (push `(with-sum-count ,lc) *loop-wrappers*))
1160 (loop-emit-body
1161 (if (eq specifically 'count)
1162 `(when ,form
1163 (setq ,(car tempvars)
1164 (1+ ,(car tempvars))))
1165 `(setq ,(car tempvars)
1166 (+ ,(car tempvars)
1167 ,form)))))))
1169 (defun loop-maxmin-collection (specifically)
1170 (multiple-value-bind (lc form)
1171 (loop-get-collection-info specifically 'maxmin 'real)
1172 (loop-check-data-type (loop-collector-dtype lc) 'real)
1173 (let ((data (loop-collector-data lc)))
1174 (unless data
1175 (setf (loop-collector-data lc)
1176 (setq data (make-loop-minimax
1177 (or (loop-collector-name lc)
1178 (gensym "LOOP-MAXMIN-"))
1179 (loop-collector-dtype lc))))
1180 (unless (loop-collector-name lc)
1181 (loop-emit-final-value (loop-minimax-answer-variable data)))
1182 (push `(with-minimax-value ,data) *loop-wrappers*))
1183 (loop-note-minimax-operation specifically data)
1184 (loop-emit-body `(loop-accumulate-minimax-value ,data
1185 ,specifically
1186 ,form)))))
1188 ;;;; value accumulation: aggregate booleans
1190 ;;; handling the ALWAYS and NEVER loop keywords
1192 ;;; Under ANSI these are not permitted to appear under conditionalization.
1193 (defun loop-do-always (restrictive negate)
1194 (let ((form (loop-get-form)))
1195 (when restrictive (loop-disallow-conditional))
1196 (loop-disallow-anonymous-collectors)
1197 (loop-emit-body `(,(if negate 'when 'unless) ,form
1198 ,(loop-construct-return nil)))
1199 (loop-emit-final-value t)))
1201 ;;; handling the THEREIS loop keyword
1203 ;;; Under ANSI this is not permitted to appear under conditionalization.
1204 (defun loop-do-thereis (restrictive)
1205 (when restrictive (loop-disallow-conditional))
1206 (loop-disallow-anonymous-collectors)
1207 (loop-emit-final-value)
1208 (loop-emit-body `(when (setq ,(loop-when-it-var) ,(loop-get-form))
1209 ,(loop-construct-return *loop-when-it-var*))))
1211 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1212 (loop-disallow-conditional kwd)
1213 (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1215 (defun loop-do-repeat ()
1216 (loop-disallow-conditional :repeat)
1217 (let* ((form (loop-get-form))
1218 (count (and (constantp form) ; FIXME: lexical environment constants
1219 (sb!int:constant-form-value form)))
1220 (type (cond ((not (realp count))
1221 'integer)
1222 ((plusp count)
1223 `(mod ,(1+ (ceiling count))))
1225 `(integer ,(ceiling count))))))
1226 (let ((var (loop-make-var (gensym "LOOP-REPEAT-") `(ceiling ,form) type)))
1227 (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-before-loop*)
1228 (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-after-body*)
1229 ;; FIXME: What should
1230 ;; (loop count t into a
1231 ;; repeat 3
1232 ;; count t into b
1233 ;; finally (return (list a b)))
1234 ;; return: (3 3) or (4 3)? PUSHes above are for the former
1235 ;; variant, L-P-B below for the latter.
1236 #+nil (loop-pseudo-body `(when (minusp (decf ,var)) (go end-loop))))))
1238 (defun loop-do-with ()
1239 (loop-disallow-conditional :with)
1240 (do ((var) (val) (dtype))
1241 (nil)
1242 (setq var (loop-pop-source)
1243 dtype (loop-optional-type var)
1244 val (cond ((loop-tequal (car *loop-source-code*) :=)
1245 (loop-pop-source)
1246 (loop-get-form))
1247 (t nil)))
1248 (loop-make-var var val dtype)
1249 (if (loop-tequal (car *loop-source-code*) :and)
1250 (loop-pop-source)
1251 (return (loop-bind-block)))))
1253 ;;;; the iteration driver
1255 (defun loop-hack-iteration (entry)
1256 (flet ((make-endtest (list-of-forms)
1257 (cond ((null list-of-forms) nil)
1258 ((member t list-of-forms) '(go end-loop))
1259 (t `(when ,(if (null (cdr (setq list-of-forms
1260 (nreverse list-of-forms))))
1261 (car list-of-forms)
1262 (cons 'or list-of-forms))
1263 (go end-loop))))))
1264 (do ((pre-step-tests nil)
1265 (steps nil)
1266 (post-step-tests nil)
1267 (pseudo-steps nil)
1268 (pre-loop-pre-step-tests nil)
1269 (pre-loop-steps nil)
1270 (pre-loop-post-step-tests nil)
1271 (pre-loop-pseudo-steps nil)
1272 (tem) (data))
1273 (nil)
1274 ;; Note that we collect endtests in reverse order, but steps in correct
1275 ;; order. MAKE-ENDTEST does the nreverse for us.
1276 (setq tem (setq data
1277 (apply (symbol-function (first entry)) (rest entry))))
1278 (and (car tem) (push (car tem) pre-step-tests))
1279 (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1280 (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1281 (setq pseudo-steps
1282 (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1283 (setq tem (cdr tem))
1284 (when *loop-emitted-body*
1285 (loop-error "iteration in LOOP follows body code"))
1286 (unless tem (setq tem data))
1287 (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1288 ;; FIXME: This (SETF FOO (NCONC FOO BAR)) idiom appears often enough
1289 ;; that it might be worth making it into an NCONCF macro.
1290 (setq pre-loop-steps
1291 (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1292 (when (car (setq tem (cdr tem)))
1293 (push (car tem) pre-loop-post-step-tests))
1294 (setq pre-loop-pseudo-steps
1295 (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1296 (unless (loop-tequal (car *loop-source-code*) :and)
1297 (setq *loop-before-loop*
1298 (list* (loop-make-desetq pre-loop-pseudo-steps)
1299 (make-endtest pre-loop-post-step-tests)
1300 (loop-make-psetq pre-loop-steps)
1301 (make-endtest pre-loop-pre-step-tests)
1302 *loop-before-loop*))
1303 (setq *loop-after-body*
1304 (list* (loop-make-desetq pseudo-steps)
1305 (make-endtest post-step-tests)
1306 (loop-make-psetq steps)
1307 (make-endtest pre-step-tests)
1308 *loop-after-body*))
1309 (loop-bind-block)
1310 (return nil))
1311 (loop-pop-source)))) ; Flush the "AND".
1313 ;;;; main iteration drivers
1315 ;;; FOR variable keyword ..args..
1316 (defun loop-do-for ()
1317 (let* ((var (loop-pop-source))
1318 (data-type (loop-optional-type var))
1319 (keyword (loop-pop-source))
1320 (first-arg nil)
1321 (tem nil))
1322 (setq first-arg (loop-get-form))
1323 (unless (and (symbolp keyword)
1324 (setq tem (loop-lookup-keyword
1325 keyword
1326 (loop-universe-for-keywords *loop-universe*))))
1327 (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP."
1328 keyword))
1329 (apply (car tem) var first-arg data-type (cdr tem))))
1331 (defun loop-when-it-var ()
1332 (or *loop-when-it-var*
1333 (setq *loop-when-it-var*
1334 (loop-make-var (gensym "LOOP-IT-") nil nil))))
1336 ;;;; various FOR/AS subdispatches
1338 ;;; ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when
1339 ;;; the THEN is omitted (other than being more stringent in its
1340 ;;; placement), and like the old "FOR x FIRST y THEN z" when the THEN
1341 ;;; is present. I.e., the first initialization occurs in the loop body
1342 ;;; (first-step), not in the variable binding phase.
1343 (defun loop-ansi-for-equals (var val data-type)
1344 (loop-make-var var nil data-type)
1345 (cond ((loop-tequal (car *loop-source-code*) :then)
1346 ;; Then we are the same as "FOR x FIRST y THEN z".
1347 (loop-pop-source)
1348 `(() (,var ,(loop-get-form)) () ()
1349 () (,var ,val) () ()))
1350 (t ;; We are the same as "FOR x = y".
1351 `(() (,var ,val) () ()))))
1353 (defun loop-for-across (var val data-type)
1354 (loop-make-var var nil data-type)
1355 (let ((vector-var (gensym "LOOP-ACROSS-VECTOR-"))
1356 (index-var (gensym "LOOP-ACROSS-INDEX-")))
1357 (multiple-value-bind (vector-form constantp vector-value)
1358 (loop-constant-fold-if-possible val 'vector)
1359 (loop-make-var
1360 vector-var vector-form
1361 (if (and (consp vector-form) (eq (car vector-form) 'the))
1362 (cadr vector-form)
1363 'vector))
1364 (loop-make-var index-var 0 'fixnum)
1365 (let* ((length 0)
1366 (length-form (cond ((not constantp)
1367 (let ((v (gensym "LOOP-ACROSS-LIMIT-")))
1368 (push `(setq ,v (length ,vector-var))
1369 *loop-prologue*)
1370 (loop-make-var v 0 'fixnum)))
1371 (t (setq length (length vector-value)))))
1372 (first-test `(>= ,index-var ,length-form))
1373 (other-test first-test)
1374 (step `(,var (aref ,vector-var ,index-var)))
1375 (pstep `(,index-var (1+ ,index-var))))
1376 (declare (fixnum length))
1377 (when constantp
1378 (setq first-test (= length 0))
1379 (when (<= length 1)
1380 (setq other-test t)))
1381 `(,other-test ,step () ,pstep
1382 ,@(and (not (eq first-test other-test))
1383 `(,first-test ,step () ,pstep)))))))
1385 ;;;; list iteration
1387 (defun loop-list-step (listvar)
1388 ;; We are not equipped to analyze whether 'FOO is the same as #'FOO
1389 ;; here in any sensible fashion, so let's give an obnoxious warning
1390 ;; whenever 'FOO is used as the stepping function.
1392 ;; While a Discerning Compiler may deal intelligently with
1393 ;; (FUNCALL 'FOO ...), not recognizing FOO may defeat some LOOP
1394 ;; optimizations.
1395 (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1396 (loop-pop-source)
1397 (loop-get-form))
1398 (t '(function cdr)))))
1399 (cond ((and (consp stepper) (eq (car stepper) 'quote))
1400 (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1401 `(funcall ,stepper ,listvar))
1402 ((and (consp stepper) (eq (car stepper) 'function))
1403 (list (cadr stepper) listvar))
1405 `(funcall ,(loop-make-var (gensym "LOOP-FN-") stepper 'function)
1406 ,listvar)))))
1408 (defun loop-for-on (var val data-type)
1409 (multiple-value-bind (list constantp list-value)
1410 (loop-constant-fold-if-possible val)
1411 (let ((listvar var))
1412 (cond ((and var (symbolp var))
1413 (loop-make-var var list data-type))
1415 (loop-make-var (setq listvar (gensym)) list 't)
1416 (loop-make-var var nil data-type)))
1417 (let ((list-step (loop-list-step listvar)))
1418 (let* ((first-endtest
1419 ;; mysterious comment from original CMU CL sources:
1420 ;; the following should use `atom' instead of `endp',
1421 ;; per [bug2428]
1422 `(atom ,listvar))
1423 (other-endtest first-endtest))
1424 (when (and constantp (listp list-value))
1425 (setq first-endtest (null list-value)))
1426 (cond ((eq var listvar)
1427 ;; The contour of the loop is different because we
1428 ;; use the user's variable...
1429 `(() (,listvar ,list-step)
1430 ,other-endtest () () () ,first-endtest ()))
1431 (t (let ((step `(,var ,listvar))
1432 (pseudo `(,listvar ,list-step)))
1433 `(,other-endtest ,step () ,pseudo
1434 ,@(and (not (eq first-endtest other-endtest))
1435 `(,first-endtest ,step () ,pseudo)))))))))))
1437 (defun loop-for-in (var val data-type)
1438 (multiple-value-bind (list constantp list-value)
1439 (loop-constant-fold-if-possible val)
1440 (let ((listvar (gensym "LOOP-LIST-")))
1441 (loop-make-var var nil data-type)
1442 (loop-make-var listvar list 'list)
1443 (let ((list-step (loop-list-step listvar)))
1444 (let* ((first-endtest `(endp ,listvar))
1445 (other-endtest first-endtest)
1446 (step `(,var (car ,listvar)))
1447 (pseudo-step `(,listvar ,list-step)))
1448 (when (and constantp (listp list-value))
1449 (setq first-endtest (null list-value)))
1450 `(,other-endtest ,step () ,pseudo-step
1451 ,@(and (not (eq first-endtest other-endtest))
1452 `(,first-endtest ,step () ,pseudo-step))))))))
1454 ;;;; iteration paths
1456 (defstruct (loop-path
1457 (:copier nil)
1458 (:predicate nil))
1459 names
1460 preposition-groups
1461 inclusive-permitted
1462 function
1463 user-data)
1465 (defun add-loop-path (names function universe
1466 &key preposition-groups inclusive-permitted user-data)
1467 (declare (type loop-universe universe))
1468 (let* ((names (sb!int:ensure-list names))
1469 (ht (loop-universe-path-keywords universe))
1470 (lp (make-loop-path
1471 :names (mapcar #'symbol-name names)
1472 :function function
1473 :user-data user-data
1474 :preposition-groups (mapcar #'sb!int:ensure-list preposition-groups)
1475 :inclusive-permitted inclusive-permitted)))
1476 (dolist (name names)
1477 (setf (gethash (symbol-name name) ht) lp))
1478 lp))
1480 ;;; Note: Path functions are allowed to use LOOP-MAKE-VAR, hack
1481 ;;; the prologue, etc.
1482 (defun loop-for-being (var val data-type)
1483 ;; FOR var BEING each/the pathname prep-phrases using-stuff... each/the =
1484 ;; EACH or THE. Not clear if it is optional, so I guess we'll warn.
1485 (let ((path nil)
1486 (data nil)
1487 (inclusive nil)
1488 (stuff nil)
1489 (initial-prepositions nil))
1490 (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1491 ((loop-tequal (car *loop-source-code*) :and)
1492 (loop-pop-source)
1493 (setq inclusive t)
1494 (unless (loop-tmember (car *loop-source-code*)
1495 '(:its :each :his :her))
1496 (loop-error "~S was found where ITS or EACH expected in LOOP iteration path syntax."
1497 (car *loop-source-code*)))
1498 (loop-pop-source)
1499 (setq path (loop-pop-source))
1500 (setq initial-prepositions `((:in ,val))))
1501 (t (loop-error "unrecognizable LOOP iteration path syntax: missing EACH or THE?")))
1502 (cond ((not (symbolp path))
1503 (loop-error
1504 "~S was found where a LOOP iteration path name was expected."
1505 path))
1506 ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1507 (loop-error "~S is not the name of a LOOP iteration path." path))
1508 ((and inclusive (not (loop-path-inclusive-permitted data)))
1509 (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1510 (let ((fun (loop-path-function data))
1511 (preps (nconc initial-prepositions
1512 (loop-collect-prepositional-phrases
1513 (loop-path-preposition-groups data)
1514 t)))
1515 (user-data (loop-path-user-data data)))
1516 (when (symbolp fun) (setq fun (symbol-function fun)))
1517 (setq stuff (if inclusive
1518 (apply fun var data-type preps :inclusive t user-data)
1519 (apply fun var data-type preps user-data))))
1520 (when *loop-named-vars*
1521 (loop-error "Unused USING vars: ~S." *loop-named-vars*))
1522 ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back).
1523 ;; Protect the system from the user and the user from himself.
1524 (unless (member (length stuff) '(6 10))
1525 (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1526 path))
1527 (do ((l (car stuff) (cdr l)) (x)) ((null l))
1528 (if (atom (setq x (car l)))
1529 (loop-make-var x nil nil)
1530 (loop-make-var (car x) (cadr x) (caddr x))))
1531 (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1532 (cddr stuff)))
1534 (defun loop-named-var (name)
1535 (let ((tem (loop-tassoc name *loop-named-vars*)))
1536 (declare (list tem))
1537 (cond ((null tem) (values (gensym) nil))
1538 (t (setq *loop-named-vars* (delete tem *loop-named-vars*))
1539 (values (cdr tem) t)))))
1541 (defun loop-collect-prepositional-phrases (preposition-groups
1542 &optional
1543 using-allowed
1544 initial-phrases)
1545 (flet ((in-group-p (x group) (car (loop-tmember x group))))
1546 (do ((token nil)
1547 (prepositional-phrases initial-phrases)
1548 (this-group nil nil)
1549 (this-prep nil nil)
1550 (disallowed-prepositions
1551 (mapcan (lambda (x)
1552 (copy-list
1553 (find (car x) preposition-groups :test #'in-group-p)))
1554 initial-phrases))
1555 (used-prepositions (mapcar #'car initial-phrases)))
1556 ((null *loop-source-code*) (nreverse prepositional-phrases))
1557 (declare (symbol this-prep))
1558 (setq token (car *loop-source-code*))
1559 (dolist (group preposition-groups)
1560 (when (setq this-prep (in-group-p token group))
1561 (return (setq this-group group))))
1562 (cond (this-group
1563 (when (member this-prep disallowed-prepositions)
1564 (loop-error
1565 (if (member this-prep used-prepositions)
1566 "A ~S prepositional phrase occurs multiply for some LOOP clause."
1567 "Preposition ~S was used when some other preposition has subsumed it.")
1568 token))
1569 (setq used-prepositions (if (listp this-group)
1570 (append this-group used-prepositions)
1571 (cons this-group used-prepositions)))
1572 (loop-pop-source)
1573 (push (list this-prep (loop-get-form)) prepositional-phrases))
1574 ((and using-allowed (loop-tequal token 'using))
1575 (loop-pop-source)
1576 (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1577 (when (cadr z)
1578 (if (setq tem (loop-tassoc (car z) *loop-named-vars*))
1579 (loop-error
1580 "The variable substitution for ~S occurs twice in a USING phrase,~@
1581 with ~S and ~S."
1582 (car z) (cadr z) (cadr tem))
1583 (push (cons (car z) (cadr z)) *loop-named-vars*)))
1584 (when (or (null *loop-source-code*)
1585 (symbolp (car *loop-source-code*)))
1586 (return nil))))
1587 (t (return (nreverse prepositional-phrases)))))))
1589 ;;;; master sequencer function
1591 (defun loop-sequencer (indexv indexv-type
1592 variable variable-type
1593 sequence-variable sequence-type
1594 step-hack default-top
1595 prep-phrases)
1596 (let ((endform nil) ; form (constant or variable) with limit value
1597 (sequencep nil) ; T if sequence arg has been provided
1598 (testfn nil) ; endtest function
1599 (test nil) ; endtest form
1600 (stepby (1+ (or (loop-typed-init indexv-type) 0))) ; our increment
1601 (stepby-constantp t)
1602 (step nil) ; step form
1603 (dir nil) ; direction of stepping: NIL, :UP, :DOWN
1604 (inclusive-iteration nil) ; T if include last index
1605 (start-given nil) ; T when prep phrase has specified start
1606 (start-value nil)
1607 (start-constantp nil)
1608 (limit-given nil) ; T when prep phrase has specified end
1609 (limit-constantp nil)
1610 (limit-value nil))
1611 (flet ((assert-index-for-arithmetic (index)
1612 (unless (atom index)
1613 (loop-error "Arithmetic index must be an atom."))))
1614 (when variable (loop-make-var variable nil variable-type))
1615 (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1616 (setq prep (caar l) form (cadar l))
1617 (case prep
1618 ((:of :in)
1619 (setq sequencep t)
1620 (loop-make-var sequence-variable form sequence-type))
1621 ((:from :downfrom :upfrom)
1622 (setq start-given t)
1623 (cond ((eq prep :downfrom) (setq dir ':down))
1624 ((eq prep :upfrom) (setq dir ':up)))
1625 (multiple-value-setq (form start-constantp start-value)
1626 (loop-constant-fold-if-possible form indexv-type))
1627 (assert-index-for-arithmetic indexv)
1628 ;; KLUDGE: loop-make-var generates a temporary symbol for
1629 ;; indexv if it is NIL. We have to use it to have the index
1630 ;; actually count
1631 (setq indexv (loop-make-var indexv form indexv-type)))
1632 ((:upto :to :downto :above :below)
1633 (cond ((loop-tequal prep :upto) (setq inclusive-iteration
1634 (setq dir ':up)))
1635 ((loop-tequal prep :to) (setq inclusive-iteration t))
1636 ((loop-tequal prep :downto) (setq inclusive-iteration
1637 (setq dir ':down)))
1638 ((loop-tequal prep :above) (setq dir ':down))
1639 ((loop-tequal prep :below) (setq dir ':up)))
1640 (setq limit-given t)
1641 (multiple-value-setq (form limit-constantp limit-value)
1642 (loop-constant-fold-if-possible form `(and ,indexv-type real)))
1643 (setq endform (if limit-constantp
1644 `',limit-value
1645 (loop-make-var
1646 (gensym "LOOP-LIMIT-") form
1647 `(and ,indexv-type real)))))
1648 (:by
1649 (multiple-value-setq (form stepby-constantp stepby)
1650 (loop-constant-fold-if-possible form
1651 `(and ,indexv-type (real (0)))))
1652 (unless stepby-constantp
1653 (loop-make-var (setq stepby (gensym "LOOP-STEP-BY-"))
1654 form
1655 `(and ,indexv-type (real (0)))
1656 t)))
1657 (t (loop-error
1658 "~S invalid preposition in sequencing or sequence path;~@
1659 maybe invalid prepositions were specified in iteration path descriptor?"
1660 prep)))
1661 (when (and odir dir (not (eq dir odir)))
1662 (loop-error
1663 "conflicting stepping directions in LOOP sequencing path"))
1664 (setq odir dir))
1665 (when (and sequence-variable (not sequencep))
1666 (loop-error "missing OF or IN phrase in sequence path"))
1667 ;; Now fill in the defaults.
1668 (cond ((not start-given)
1669 ;; default start
1670 ;; DUPLICATE KLUDGE: loop-make-var generates a temporary
1671 ;; symbol for indexv if it is NIL. See also the comment in
1672 ;; the (:from :downfrom :upfrom) case
1673 (assert-index-for-arithmetic indexv)
1674 (setq indexv
1675 (loop-make-var
1676 indexv
1677 (setq start-constantp t
1678 start-value (or (loop-typed-init indexv-type) 0))
1679 `(and ,indexv-type real))))
1680 (limit-given
1681 ;; if both start and limit are given, they had better both
1682 ;; be REAL. We already enforce the REALness of LIMIT,
1683 ;; above; here's the KLUDGE to enforce the type of START.
1684 (flet ((type-declaration-of (x)
1685 (and (eq (car x) 'type) (caddr x))))
1686 (let ((decl (find indexv *loop-declarations*
1687 :key #'type-declaration-of))
1688 (%decl (find indexv *loop-declarations*
1689 :key #'type-declaration-of
1690 :from-end t)))
1691 (sb!int:aver (eq decl %decl))
1692 (when decl
1693 (setf (cadr decl)
1694 `(and real ,(cadr decl))))))))
1695 (cond ((member dir '(nil :up))
1696 (when (or limit-given default-top)
1697 (unless limit-given
1698 (loop-make-var (setq endform (gensym "LOOP-SEQ-LIMIT-"))
1700 indexv-type)
1701 (push `(setq ,endform ,default-top) *loop-prologue*))
1702 (setq testfn (if inclusive-iteration '> '>=)))
1703 (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1704 (t (unless start-given
1705 (unless default-top
1706 (loop-error "don't know where to start stepping"))
1707 (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1708 (when (and default-top (not endform))
1709 (setq endform (loop-typed-init indexv-type)
1710 inclusive-iteration t))
1711 (when endform (setq testfn (if inclusive-iteration '< '<=)))
1712 (setq step
1713 (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1714 (when testfn
1715 (setq test
1716 `(,testfn ,indexv ,endform)))
1717 (when step-hack
1718 (setq step-hack
1719 `(,variable ,step-hack)))
1720 (let ((first-test test) (remaining-tests test))
1721 ;; As far as I can tell, the effect of the following code is
1722 ;; to detect cases where we know statically whether the first
1723 ;; iteration of the loop will be executed. Depending on the
1724 ;; situation, we can either:
1725 ;; a) save one jump and one comparison per loop (not per iteration)
1726 ;; when it will get executed
1727 ;; b) remove the loop body completely when it won't be executed
1729 ;; Noble goals. However, the code generated in case a) will
1730 ;; fool the loop induction variable detection, and cause
1731 ;; code like (LOOP FOR I TO 10 ...) to use generic addition
1732 ;; (bug #278a).
1734 ;; Since the gain in case a) is rather minimal and Python is
1735 ;; generally smart enough to handle b) without any extra
1736 ;; support from the loop macro, I've disabled this code for
1737 ;; now. The code and the comment left here in case somebody
1738 ;; extends the induction variable bound detection to work
1739 ;; with code where the stepping precedes the test.
1740 ;; -- JES 2005-11-30
1741 #+nil
1742 (when (and stepby-constantp start-constantp limit-constantp
1743 (realp start-value) (realp limit-value))
1744 (when (setq first-test
1745 (funcall (symbol-function testfn)
1746 start-value
1747 limit-value))
1748 (setq remaining-tests t)))
1749 `(() (,indexv ,step)
1750 ,remaining-tests ,step-hack () () ,first-test ,step-hack)))))
1752 ;;;; interfaces to the master sequencer
1754 (defun loop-for-arithmetic (var val data-type kwd)
1755 (loop-sequencer
1756 var (loop-check-data-type data-type 'number)
1757 nil nil nil nil nil nil
1758 (loop-collect-prepositional-phrases
1759 '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1760 nil (list (list kwd val)))))
1763 ;;;; builtin LOOP iteration paths
1766 (loop for v being the hash-values of ht do (print v))
1767 (loop for k being the hash-keys of ht do (print k))
1768 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1769 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1772 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
1773 &key (which (sb!int:missing-arg)))
1774 (declare (type (member :hash-key :hash-value) which))
1775 (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1776 (loop-error "too many prepositions!"))
1777 ((null prep-phrases)
1778 (loop-error "missing OF or IN in ~S iteration path")))
1779 (let ((ht-var (gensym "LOOP-HASHTAB-"))
1780 (next-fn (gensym "LOOP-HASHTAB-NEXT-"))
1781 (dummy-predicate-var nil)
1782 (post-steps nil))
1783 (multiple-value-bind (other-var other-p)
1784 (loop-named-var (ecase which
1785 (:hash-key 'hash-value)
1786 (:hash-value 'hash-key)))
1787 ;; @@@@ LOOP-NAMED-VAR returns a second value of T if the name
1788 ;; was actually specified, so clever code can throw away the
1789 ;; GENSYM'ed-up variable if it isn't really needed. The
1790 ;; following is for those implementations in which we cannot put
1791 ;; dummy NILs into MULTIPLE-VALUE-SETQ variable lists.
1792 (setq other-p t
1793 dummy-predicate-var (loop-when-it-var))
1794 (let* ((key-var nil)
1795 (val-var nil)
1796 (variable (or variable (gensym "LOOP-HASH-VAR-TEMP-")))
1797 (bindings `((,variable nil ,data-type)
1798 (,ht-var ,(cadar prep-phrases))
1799 ,@(and other-p other-var `((,other-var nil))))))
1800 (ecase which
1801 (:hash-key (setq key-var variable
1802 val-var (and other-p other-var)))
1803 (:hash-value (setq key-var (and other-p other-var)
1804 val-var variable)))
1805 (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1806 (when (or (consp key-var) data-type)
1807 (setq post-steps
1808 `(,key-var ,(setq key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1809 ,@post-steps))
1810 (push `(,key-var nil) bindings))
1811 (when (or (consp val-var) data-type)
1812 (setq post-steps
1813 `(,val-var ,(setq val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1814 ,@post-steps))
1815 (push `(,val-var nil) bindings))
1816 `(,bindings ;bindings
1817 () ;prologue
1818 () ;pre-test
1819 () ;parallel steps
1820 (not (multiple-value-setq (,dummy-predicate-var ,key-var ,val-var)
1821 (,next-fn))) ;post-test
1822 ,post-steps)))))
1824 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
1825 &key symbol-types)
1826 (cond ((and prep-phrases (cdr prep-phrases))
1827 (loop-error "Too many prepositions!"))
1828 ((and prep-phrases (not (member (caar prep-phrases) '(:in :of))))
1829 (sb!int:bug "Unknown preposition ~S." (caar prep-phrases))))
1830 (unless (symbolp variable)
1831 (loop-error "Destructuring is not valid for package symbol iteration."))
1832 (let ((pkg-var (gensym "LOOP-PKGSYM-"))
1833 (next-fn (gensym "LOOP-PKGSYM-NEXT-"))
1834 (variable (or variable (gensym "LOOP-PKGSYM-VAR-")))
1835 (package (or (cadar prep-phrases) '*package*)))
1836 (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types))
1837 *loop-wrappers*)
1838 `(((,variable nil ,data-type) (,pkg-var ,package))
1842 (not (multiple-value-setq (,(loop-when-it-var)
1843 ,variable)
1844 (,next-fn)))
1845 ())))
1847 ;;;; ANSI LOOP
1849 (defun !make-ansi-loop-universe ()
1850 (let ((w (!make-standard-loop-universe
1851 :keywords '((named (loop-do-named))
1852 (initially (loop-do-initially))
1853 (finally (loop-do-finally))
1854 (do (loop-do-do))
1855 (doing (loop-do-do))
1856 (return (loop-do-return))
1857 (collect (loop-list-collection list))
1858 (collecting (loop-list-collection list))
1859 (append (loop-list-collection append))
1860 (appending (loop-list-collection append))
1861 (nconc (loop-list-collection nconc))
1862 (nconcing (loop-list-collection nconc))
1863 (count (loop-sum-collection count
1864 ;; This could be REAL, but when
1865 ;; combined with SUM, it has to be
1866 ;; NUMBER.
1867 number
1868 fixnum))
1869 (counting (loop-sum-collection count
1870 number
1871 fixnum))
1872 (sum (loop-sum-collection sum number number))
1873 (summing (loop-sum-collection sum number number))
1874 (maximize (loop-maxmin-collection max))
1875 (minimize (loop-maxmin-collection min))
1876 (maximizing (loop-maxmin-collection max))
1877 (minimizing (loop-maxmin-collection min))
1878 (always (loop-do-always t nil)) ; Normal, do always
1879 (never (loop-do-always t t)) ; Negate test on always.
1880 (thereis (loop-do-thereis t))
1881 (while (loop-do-while nil :while)) ; Normal, do while
1882 (until (loop-do-while t :until)) ;Negate test on while
1883 (when (loop-do-if when nil)) ; Normal, do when
1884 (if (loop-do-if if nil)) ; synonymous
1885 (unless (loop-do-if unless t)) ; Negate test on when
1886 (with (loop-do-with))
1887 (repeat (loop-do-repeat)))
1888 :for-keywords '((= (loop-ansi-for-equals))
1889 (across (loop-for-across))
1890 (in (loop-for-in))
1891 (on (loop-for-on))
1892 (from (loop-for-arithmetic :from))
1893 (downfrom (loop-for-arithmetic :downfrom))
1894 (upfrom (loop-for-arithmetic :upfrom))
1895 (below (loop-for-arithmetic :below))
1896 (above (loop-for-arithmetic :above))
1897 (to (loop-for-arithmetic :to))
1898 (upto (loop-for-arithmetic :upto))
1899 (downto (loop-for-arithmetic :downto))
1900 (by (loop-for-arithmetic :by))
1901 (being (loop-for-being)))
1902 :iteration-keywords '((for (loop-do-for))
1903 (as (loop-do-for)))
1904 :type-symbols sb!kernel::*!standard-type-names*
1905 :type-keywords nil)))
1906 (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
1907 :preposition-groups '((:of :in))
1908 :inclusive-permitted nil
1909 :user-data '(:which :hash-key))
1910 (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
1911 :preposition-groups '((:of :in))
1912 :inclusive-permitted nil
1913 :user-data '(:which :hash-value))
1914 (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
1915 :preposition-groups '((:of :in))
1916 :inclusive-permitted nil
1917 :user-data '(:symbol-types (:internal
1918 :external
1919 :inherited)))
1920 (add-loop-path '(external-symbol external-symbols)
1921 'loop-package-symbols-iteration-path w
1922 :preposition-groups '((:of :in))
1923 :inclusive-permitted nil
1924 :user-data '(:symbol-types (:external)))
1925 (add-loop-path '(present-symbol present-symbols)
1926 'loop-package-symbols-iteration-path w
1927 :preposition-groups '((:of :in))
1928 :inclusive-permitted nil
1929 :user-data '(:symbol-types (:internal
1930 :external)))
1933 (defparameter *loop-ansi-universe*
1934 (!make-ansi-loop-universe))
1936 (defun loop-standard-expansion (keywords-and-forms environment universe)
1937 (if (and keywords-and-forms (symbolp (car keywords-and-forms)))
1938 (loop-translate keywords-and-forms environment universe)
1939 (let ((tag (gensym)))
1940 `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
1942 (sb!xc:defmacro loop (&environment env &rest keywords-and-forms)
1943 (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))
1945 (sb!xc:defmacro loop-finish ()
1946 #!+sb-doc
1947 "Cause the iteration to terminate \"normally\", the same as implicit
1948 termination by an iteration driving clause, or by use of WHILE or
1949 UNTIL -- the epilogue code (if any) will be run, and any implicitly
1950 collected result will be returned as the value of the LOOP."
1951 '(go end-loop))