Eliminate style-warning about undefined type GLOBAL-VAR
[sbcl.git] / src / code / loop.lisp
blobae93b203f39710a50bbc8973faf34d5007d51571
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 ;;; Transform the LOOP kind of destructuring into the DESTRUCTURING-BIND kind
561 ;;; basically by adding &optional and ignored &rest dotted list
562 (defun transform-destructuring (tree)
563 (let (ignores)
564 (labels ((transform (tree)
565 (do ((result (list '&optional))
566 (cdr tree (cdr cdr)))
567 (())
568 (cond ((null cdr)
569 (return (nreconc result
570 (car (push (gensym "LOOP-IGNORED-")
571 ignores)))))
572 ((atom cdr)
573 (return (nreconc result cdr)))
574 ((consp (car cdr))
575 (push (list (transform (car cdr))) result))
576 ((null (car cdr))
577 (push (car (push (gensym "LOOP-IGNORED-")
578 ignores))
579 result))
581 (push (car cdr) result))))))
582 (values (transform tree) ignores))))
584 (sb!int:defmacro-mundanely loop-destructuring-bind
585 (lambda-list args &rest body)
586 (multiple-value-bind (d-lambda-list ignores)
587 (transform-destructuring lambda-list)
588 `(destructuring-bind ,d-lambda-list ,args
589 (declare (ignore ,@ignores))
590 ,@body)))
592 (defun loop-build-destructuring-bindings (crocks forms)
593 (if crocks
594 `((loop-destructuring-bind ,(car crocks) ,(cadr crocks)
595 ,@(loop-build-destructuring-bindings (cddr crocks) forms)))
596 forms))
598 (defun loop-translate (*loop-source-code*
599 *loop-macro-environment*
600 *loop-universe*)
601 (let ((*loop-original-source-code* *loop-source-code*)
602 (*loop-source-context* nil)
603 (*loop-vars* nil)
604 (*loop-named-vars* nil)
605 (*loop-declarations* nil)
606 (*loop-desetq-declarations* nil)
607 (*loop-desetq* nil)
608 (*loop-bind-stack* nil)
609 (*loop-prologue* nil)
610 (*loop-wrappers* nil)
611 (*loop-before-loop* nil)
612 (*loop-body* nil)
613 (*loop-emitted-body* nil)
614 (*loop-after-body* nil)
615 (*loop-epilogue* nil)
616 (*loop-after-epilogue* nil)
617 (*loop-final-value-culprit* nil)
618 (*loop-inside-conditional* nil)
619 (*loop-when-it-var* nil)
620 (*loop-never-stepped-var* nil)
621 (*loop-names* nil)
622 (*loop-collection-cruft* nil))
623 (loop-iteration-driver)
624 (loop-bind-block)
625 (let ((answer `(loop-body
626 ,(nreverse *loop-prologue*)
627 ,(nreverse *loop-before-loop*)
628 ,(nreverse *loop-body*)
629 ,(nreverse *loop-after-body*)
630 ,(nreconc *loop-epilogue*
631 (nreverse *loop-after-epilogue*)))))
632 (dolist (entry *loop-bind-stack*)
633 (destructuring-bind (vars dcls desetq desetq-decls wrappers) entry
634 (dolist (w wrappers)
635 (setq answer (append w (list answer))))
636 (when (or vars dcls desetq)
637 (let ((forms (list answer)))
638 (when desetq-decls
639 (push `(declare ,@desetq-decls) forms))
640 (setq answer `(,(if vars 'let 'locally)
641 ,vars
642 (declare ,@dcls)
643 ,@(loop-build-destructuring-bindings desetq
644 forms)))))))
645 (do () (nil)
646 (setq answer `(block ,(pop *loop-names*) ,answer))
647 (unless *loop-names* (return nil)))
648 answer)))
650 (defun loop-iteration-driver ()
651 (do ()
652 ((null *loop-source-code*))
653 (let ((keyword (car *loop-source-code*)) (tem nil))
654 (cond ((not (symbolp keyword))
655 (loop-error "~S found where LOOP keyword expected" keyword))
656 (t (setq *loop-source-context* *loop-source-code*)
657 (loop-pop-source)
658 (cond ((setq tem
659 (loop-lookup-keyword keyword
660 (loop-universe-keywords
661 *loop-universe*)))
662 ;; It's a "miscellaneous" toplevel LOOP keyword (DO,
663 ;; COLLECT, NAMED, etc.)
664 (apply (symbol-function (first tem)) (rest tem)))
665 ((setq tem
666 (loop-lookup-keyword keyword
667 (loop-universe-iteration-keywords *loop-universe*)))
668 (loop-hack-iteration tem))
669 ((loop-tmember keyword '(and else))
670 ;; The alternative is to ignore it, i.e. let it go
671 ;; around to the next keyword...
672 (loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
673 keyword
674 (car *loop-source-code*)
675 (cadr *loop-source-code*)))
676 (t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
678 (defun loop-pop-source ()
679 (if *loop-source-code*
680 (pop *loop-source-code*)
681 (loop-error "LOOP source code ran out when another token was expected.")))
683 (defun loop-get-form ()
684 (if *loop-source-code*
685 (loop-pop-source)
686 (loop-error "LOOP code ran out where a form was expected.")))
688 (defun loop-get-compound-form ()
689 (let ((form (loop-get-form)))
690 (unless (consp form)
691 (loop-error "A compound form was expected, but ~S found." form))
692 form))
694 (defun loop-get-progn ()
695 (do ((forms (list (loop-get-compound-form))
696 (cons (loop-get-compound-form) forms))
697 (nextform (car *loop-source-code*)
698 (car *loop-source-code*)))
699 ((atom nextform)
700 (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
702 (defun loop-construct-return (form)
703 `(return-from ,(car *loop-names*) ,form))
705 (defun loop-pseudo-body (form)
706 (cond ((or *loop-emitted-body* *loop-inside-conditional*)
707 (push form *loop-body*))
708 (t (push form *loop-before-loop*) (push form *loop-after-body*))))
710 (defun loop-emit-body (form)
711 (setq *loop-emitted-body* t)
712 (loop-pseudo-body form))
714 (defun loop-emit-final-value (&optional (form nil form-supplied-p))
715 (when form-supplied-p
716 (push (loop-construct-return form) *loop-after-epilogue*))
717 (setq *loop-final-value-culprit* (car *loop-source-context*)))
719 (defun loop-disallow-conditional (&optional kwd)
720 (when *loop-inside-conditional*
721 (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
723 (defun loop-disallow-anonymous-collectors ()
724 (when (find-if-not 'loop-collector-name *loop-collection-cruft*)
725 (loop-error "This LOOP clause is not permitted with anonymous collectors.")))
727 (defun loop-disallow-aggregate-booleans ()
728 (when (loop-tmember *loop-final-value-culprit* '(always never thereis))
729 (loop-error "This anonymous collection LOOP clause is not permitted with aggregate booleans.")))
731 ;;;; loop types
733 (defun loop-typed-init (data-type &optional step-var-p)
734 ;; FIXME: can't tell if unsupplied or NIL, but it has to be rare.
735 (when data-type
736 (let ((ctype (sb!kernel:specifier-type data-type)))
737 ;; FIXME: use the ctype for the rest of the type operations, now
738 ;; that it's parsed.
739 (cond ((eql ctype sb!kernel:*empty-type*)
740 (values nil t))
741 ((sb!xc:subtypep data-type 'number)
742 (let ((init (if step-var-p 1 0)))
743 (flet ((like (&rest types)
744 (coerce init (find-if (lambda (type)
745 (sb!xc:subtypep data-type type))
746 types))))
747 (cond ((sb!xc:subtypep data-type 'float)
748 (like 'single-float 'double-float
749 'short-float 'long-float 'float))
750 ((sb!xc:subtypep data-type '(complex float))
751 (like '(complex single-float)
752 '(complex double-float)
753 '(complex short-float)
754 '(complex long-float)
755 '(complex float)))
757 init)))))
758 ((sb!xc:subtypep data-type 'vector)
759 (when (sb!kernel:array-type-p ctype)
760 (let ((etype (sb!kernel:type-*-to-t
761 (sb!kernel:array-type-specialized-element-type ctype))))
762 (make-array 0 :element-type (sb!kernel:type-specifier etype)))))
763 #!+sb-unicode
764 ((sb!xc:subtypep data-type 'extended-char)
765 (code-char sb!int:base-char-code-limit))
766 ((sb!xc:subtypep data-type 'character)
767 #\x)
769 nil)))))
771 (defun loop-optional-type (&optional variable)
772 ;; No variable specified implies that no destructuring is permissible.
773 (and *loop-source-code* ; Don't get confused by NILs..
774 (let ((z (car *loop-source-code*)))
775 (cond ((loop-tequal z 'of-type)
776 ;; This is the syntactically unambigous form in that
777 ;; the form of the type specifier does not matter.
778 ;; Also, it is assumed that the type specifier is
779 ;; unambiguously, and without need of translation, a
780 ;; common lisp type specifier or pattern (matching the
781 ;; variable) thereof.
782 (loop-pop-source)
783 (loop-pop-source))
785 ((symbolp z)
786 ;; This is the (sort of) "old" syntax, even though we
787 ;; didn't used to support all of these type symbols.
788 (let ((type-spec (or (gethash z
789 (loop-universe-type-symbols
790 *loop-universe*))
791 (gethash (symbol-name z)
792 (loop-universe-type-keywords
793 *loop-universe*)))))
794 (when type-spec
795 (loop-pop-source)
796 type-spec)))
798 ;; This is our sort-of old syntax. But this is only
799 ;; valid for when we are destructuring, so we will be
800 ;; compulsive (should we really be?) and require that
801 ;; we in fact be doing variable destructuring here. We
802 ;; must translate the old keyword pattern typespec
803 ;; into a fully-specified pattern of real type
804 ;; specifiers here.
805 (if (consp variable)
806 (unless (consp z)
807 (loop-error
808 "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
810 (loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
811 (loop-pop-source)
812 (labels ((translate (k v)
813 (cond ((null k) nil)
814 ((atom k)
815 (replicate
816 (or (gethash k
817 (loop-universe-type-symbols
818 *loop-universe*))
819 (gethash (symbol-name k)
820 (loop-universe-type-keywords
821 *loop-universe*))
822 (loop-error
823 "The destructuring type pattern ~S contains the unrecognized type keyword ~S."
824 z k))
826 ((atom v)
827 (loop-error
828 "The destructuring type pattern ~S doesn't match the variable pattern ~S."
829 z variable))
830 (t (cons (translate (car k) (car v))
831 (translate (cdr k) (cdr v))))))
832 (replicate (typ v)
833 (if (atom v)
835 (cons (replicate typ (car v))
836 (replicate typ (cdr v))))))
837 (translate z variable)))))))
839 ;;;; loop variables
841 (defun loop-bind-block ()
842 (when (or *loop-vars* *loop-declarations* *loop-wrappers*
843 *loop-desetq*)
844 (push (list (nreverse *loop-vars*)
845 *loop-declarations*
846 *loop-desetq*
847 *loop-desetq-declarations*
848 *loop-wrappers*)
849 *loop-bind-stack*)
850 (setq *loop-vars* nil
851 *loop-declarations* nil
852 *loop-desetq* nil
853 *loop-desetq-declarations* nil
854 *loop-wrappers* nil)))
856 (defun check-var-name (name &optional (context ""))
857 (labels ((map-name (function name)
858 (do ((x (pop name) (pop name)))
859 (())
860 (typecase x
861 (null)
862 (cons (map-name function x))
863 (symbol (funcall function x))
865 (loop-error "Bad variable ~s~a" x context)))
866 (typecase name
867 (cons)
868 (null
869 (return))
870 (symbol
871 (funcall function name)
872 (return))
874 (loop-error "Bad variable ~s~a" name context)))))
875 (duplicate (x)
876 (loop-error "Duplicated variable ~s~a" x context))
877 (find-in-desetq (name desetqs)
878 (do* ((desetq desetqs (cddr desetq))
879 (var (car desetq) (car desetq)))
880 ((null desetq))
881 (map-name (lambda (x)
882 (when (eql name x)
883 (duplicate name)))
884 var))))
885 (cond ((consp name)
886 (map-name (lambda (x) (check-var-name x context)) name))
887 ((assoc name *loop-vars*)
888 (duplicate name))
889 ((find-in-desetq name *loop-desetq*))
891 (do ((entry *loop-bind-stack* (cdr entry)))
892 (nil)
893 (cond
894 ((null entry) (return nil))
895 ((assoc name (caar entry) :test #'eq)
896 (duplicate name))
898 (find-in-desetq name (caddar entry)))))))))
900 (defun loop-make-var (name initialization dtype &optional step-var-p)
901 (cond ((null name)
902 (setq name (gensym "LOOP-IGNORE-"))
903 (push (list name (or initialization (loop-typed-init dtype step-var-p)))
904 *loop-vars*)
905 (push `(ignore ,name) *loop-declarations*)
906 (loop-declare-var name dtype))
907 ((atom name)
908 (check-var-name name)
909 (loop-declare-var name dtype :step-var-p step-var-p
910 :initialization initialization)
911 ;; We use ASSOC on this list to check for duplications (above),
912 ;; so don't optimize out this list:
913 (push (list name (or initialization (loop-typed-init dtype step-var-p)))
914 *loop-vars*))
915 (initialization
916 (check-var-name name)
917 (let ((newvar (gensym "LOOP-DESTRUCTURE-")))
918 (loop-declare-var name dtype :desetq t)
919 (push (list newvar initialization) *loop-vars*)
920 ;; *LOOP-DESETQ* gathered in reverse order.
921 (setq *loop-desetq*
922 (list* name newvar *loop-desetq*))))
924 (let ((tcar nil) (tcdr nil))
925 (if (atom dtype) (setq tcar (setq tcdr dtype))
926 (setq tcar (car dtype) tcdr (cdr dtype)))
927 (loop-make-var (car name) nil tcar)
928 (when (cdr name)
929 (loop-make-var (cdr name) nil tcdr)))))
930 name)
932 ;;; Find a suitable type for default initialization
933 (defun type-for-default-init (type &optional step-var-p)
934 (multiple-value-bind (init empty-type)
935 (loop-typed-init type step-var-p)
936 (values
937 (cond (empty-type
938 ;; Don't wrap empty types `(or ...), otherwise the will no
939 ;; longer be empty and the compiler won't produce
940 ;; warnings.
941 type)
942 ((sb!xc:typep init type)
943 type)
944 ((sb!xc:typep init '(simple-array * (*)))
945 ;; type-of lets the size in
946 `(or (simple-array ,(array-element-type init) (*)) ,type))
948 `(or ,(sb!xc:type-of init) ,type)))
949 init)))
951 (defun loop-declare-var (name dtype &key step-var-p initialization
952 desetq)
953 (cond ((or (null name) (null dtype) (eq dtype t)) nil)
954 ((symbolp name)
955 (unless (or (sb!xc:subtypep t dtype)
956 (and (eq (find-package :cl) (symbol-package name))
957 (eq :special (sb!int:info :variable :kind name))))
958 (let ((dtype `(type ,(if initialization
959 dtype
960 (type-for-default-init dtype step-var-p))
961 ,name)))
962 (if desetq
963 (push dtype *loop-desetq-declarations*)
964 (push dtype *loop-declarations*)))))
965 ((consp name)
966 (cond ((consp dtype)
967 (loop-declare-var (car name) (car dtype)
968 :desetq desetq)
969 (loop-declare-var (cdr name) (cdr dtype)
970 :desetq desetq))
971 (t (loop-declare-var (car name) dtype
972 :desetq desetq)
973 (loop-declare-var (cdr name) dtype
974 :desetq desetq))))
975 (t (error "invalid LOOP variable passed in: ~S" name))))
977 (defun loop-maybe-bind-form (form data-type)
978 (if (constantp form)
979 form
980 (loop-make-var (gensym "LOOP-BIND-") form data-type)))
982 (defun loop-do-if (for negatep)
983 (let ((form (loop-get-form))
984 (*loop-inside-conditional* t)
985 (it-p nil)
986 (first-clause-p t))
987 (flet ((get-clause (for)
988 (do ((body nil)) (nil)
989 (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
990 (cond ((not (symbolp key))
991 (loop-error
992 "~S found where keyword expected getting LOOP clause after ~S"
993 key for))
994 (t (setq *loop-source-context* *loop-source-code*)
995 (loop-pop-source)
996 (when (and (loop-tequal (car *loop-source-code*) 'it)
997 first-clause-p)
998 (setq *loop-source-code*
999 (cons (or it-p
1000 (setq it-p
1001 (loop-when-it-var)))
1002 (cdr *loop-source-code*))))
1003 (cond ((or (not (setq data (loop-lookup-keyword
1004 key (loop-universe-keywords *loop-universe*))))
1005 (progn (apply (symbol-function (car data))
1006 (cdr data))
1007 (null *loop-body*)))
1008 (loop-error
1009 "~S does not introduce a LOOP clause that can follow ~S."
1010 key for))
1011 (t (setq body (nreconc *loop-body* body)))))))
1012 (setq first-clause-p nil)
1013 (if (loop-tequal (car *loop-source-code*) :and)
1014 (loop-pop-source)
1015 (return (if (cdr body)
1016 `(progn ,@(nreverse body))
1017 (car body)))))))
1018 (let ((then (get-clause for))
1019 (else (when (loop-tequal (car *loop-source-code*) :else)
1020 (loop-pop-source)
1021 (list (get-clause :else)))))
1022 (when (loop-tequal (car *loop-source-code*) :end)
1023 (loop-pop-source))
1024 (when it-p (setq form `(setq ,it-p ,form)))
1025 (loop-pseudo-body
1026 `(if ,(if negatep `(not ,form) form)
1027 ,then
1028 ,@else))))))
1030 (defun loop-do-initially ()
1031 (loop-disallow-conditional :initially)
1032 (push (loop-get-progn) *loop-prologue*))
1034 (defun loop-do-finally ()
1035 (loop-disallow-conditional :finally)
1036 (push (loop-get-progn) *loop-epilogue*))
1038 (defun loop-do-do ()
1039 (loop-emit-body (loop-get-progn)))
1041 (defun loop-do-named ()
1042 (let ((name (loop-pop-source)))
1043 (unless (symbolp name)
1044 (loop-error "~S is an invalid name for your LOOP" name))
1045 (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1046 (loop-error "The NAMED ~S clause occurs too late." name))
1047 (when *loop-names*
1048 (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1049 (car *loop-names*) name))
1050 (setq *loop-names* (list name))))
1052 (defun loop-do-return ()
1053 (loop-emit-body (loop-construct-return (loop-get-form))))
1055 ;;;; value accumulation: LIST
1057 (defstruct (loop-collector
1058 (:copier nil)
1059 (:predicate nil))
1060 name
1061 class
1062 (history nil)
1063 (tempvars nil)
1064 specified-type
1065 dtype
1066 (data nil)) ;collector-specific data
1068 (sb!int:defmacro-mundanely with-sum-count (lc &body body)
1069 (let* ((type (loop-collector-dtype lc))
1070 (temp-var (car (loop-collector-tempvars lc))))
1071 (multiple-value-bind (type init)
1072 (type-for-default-init type)
1073 `(let ((,temp-var ,init))
1074 (declare (type ,type ,temp-var))
1075 ,@body))))
1077 (defun loop-get-collection-info (collector class default-type)
1078 (let ((form (loop-get-form))
1079 (name (when (loop-tequal (car *loop-source-code*) 'into)
1080 (loop-pop-source)
1081 (loop-pop-source))))
1082 (when (not (symbolp name))
1083 (loop-error "The value accumulation recipient name, ~S, is not a symbol." name))
1084 (unless name
1085 (loop-disallow-aggregate-booleans))
1086 (let* ((specified-type (loop-optional-type))
1087 (dtype (or specified-type default-type))
1088 (cruft (find (the symbol name) *loop-collection-cruft*
1089 :key #'loop-collector-name)))
1090 (cond ((not cruft)
1091 (check-var-name name " in INTO clause")
1092 (push (setq cruft (make-loop-collector
1093 :name name :class class
1094 :history (list collector)
1095 :specified-type specified-type
1096 :dtype dtype))
1097 *loop-collection-cruft*))
1098 (t (unless (eq (loop-collector-class cruft) class)
1099 (loop-error
1100 "incompatible kinds of LOOP value accumulation specified for collecting~@
1101 ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S"
1102 name (car (loop-collector-history cruft)) collector))
1103 (cond ((equal dtype (loop-collector-dtype cruft)))
1104 ((and (null specified-type)
1105 (null (loop-collector-specified-type cruft)))
1106 ;; Unionize types only for default types, most
1107 ;; likely, SUM and COUNT which have number and
1108 ;; fixnum respectively.
1109 (setf (loop-collector-dtype cruft)
1110 (sb!kernel:type-specifier
1111 (sb!kernel:type-union
1112 (sb!kernel:specifier-type dtype)
1113 (sb!kernel:specifier-type (loop-collector-dtype cruft))))))
1115 (loop-warn
1116 "unequal datatypes specified in different LOOP value accumulations~@
1117 into ~S: ~S and ~S"
1118 name dtype (loop-collector-dtype cruft))
1119 (when (eq (loop-collector-dtype cruft) t)
1120 (setf (loop-collector-dtype cruft) dtype))))
1121 (push collector (loop-collector-history cruft))))
1122 (values cruft form))))
1124 (defun loop-list-collection (specifically) ; NCONC, LIST, or APPEND
1125 (multiple-value-bind (lc form)
1126 (loop-get-collection-info specifically 'list 'list)
1127 (let ((tempvars (loop-collector-tempvars lc)))
1128 (unless tempvars
1129 (setf (loop-collector-tempvars lc)
1130 (setq tempvars (list* (gensym "LOOP-LIST-HEAD-")
1131 (gensym "LOOP-LIST-TAIL-")
1132 (and (loop-collector-name lc)
1133 (list (loop-collector-name lc))))))
1134 (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1135 (unless (loop-collector-name lc)
1136 (loop-emit-final-value `(loop-collect-answer ,(car tempvars)
1137 ,@(cddr tempvars)))))
1138 (ecase specifically
1139 (list (setq form `(list ,form)))
1140 (nconc nil)
1141 (append (unless (and (consp form) (eq (car form) 'list))
1142 (setq form `(copy-list ,form)))))
1143 (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1145 ;;;; value accumulation: MAX, MIN, SUM, COUNT
1147 (defun loop-sum-collection (specifically required-type default-type);SUM, COUNT
1148 (multiple-value-bind (lc form)
1149 (loop-get-collection-info specifically 'sum default-type)
1150 (loop-check-data-type (loop-collector-dtype lc) required-type)
1151 (let ((tempvars (loop-collector-tempvars lc)))
1152 (unless tempvars
1153 (setf (loop-collector-tempvars lc)
1154 (setq tempvars (list (or (loop-collector-name lc)
1155 (gensym "LOOP-SUM-")))))
1156 (unless (loop-collector-name lc)
1157 (loop-emit-final-value (car (loop-collector-tempvars lc))))
1158 (push `(with-sum-count ,lc) *loop-wrappers*))
1159 (loop-emit-body
1160 (if (eq specifically 'count)
1161 `(when ,form
1162 (setq ,(car tempvars)
1163 (1+ ,(car tempvars))))
1164 `(setq ,(car tempvars)
1165 (+ ,(car tempvars)
1166 ,form)))))))
1168 (defun loop-maxmin-collection (specifically)
1169 (multiple-value-bind (lc form)
1170 (loop-get-collection-info specifically 'maxmin 'real)
1171 (loop-check-data-type (loop-collector-dtype lc) 'real)
1172 (let ((data (loop-collector-data lc)))
1173 (unless data
1174 (setf (loop-collector-data lc)
1175 (setq data (make-loop-minimax
1176 (or (loop-collector-name lc)
1177 (gensym "LOOP-MAXMIN-"))
1178 (loop-collector-dtype lc))))
1179 (unless (loop-collector-name lc)
1180 (loop-emit-final-value (loop-minimax-answer-variable data)))
1181 (push `(with-minimax-value ,data) *loop-wrappers*))
1182 (loop-note-minimax-operation specifically data)
1183 (loop-emit-body `(loop-accumulate-minimax-value ,data
1184 ,specifically
1185 ,form)))))
1187 ;;;; value accumulation: aggregate booleans
1189 ;;; handling the ALWAYS and NEVER loop keywords
1191 ;;; Under ANSI these are not permitted to appear under conditionalization.
1192 (defun loop-do-always (restrictive negate)
1193 (let ((form (loop-get-form)))
1194 (when restrictive (loop-disallow-conditional))
1195 (loop-disallow-anonymous-collectors)
1196 (loop-emit-body `(,(if negate 'when 'unless) ,form
1197 ,(loop-construct-return nil)))
1198 (loop-emit-final-value t)))
1200 ;;; handling the THEREIS loop keyword
1202 ;;; Under ANSI this is not permitted to appear under conditionalization.
1203 (defun loop-do-thereis (restrictive)
1204 (when restrictive (loop-disallow-conditional))
1205 (loop-disallow-anonymous-collectors)
1206 (loop-emit-final-value)
1207 (loop-emit-body `(when (setq ,(loop-when-it-var) ,(loop-get-form))
1208 ,(loop-construct-return *loop-when-it-var*))))
1210 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1211 (loop-disallow-conditional kwd)
1212 (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1214 (defun loop-do-repeat ()
1215 (loop-disallow-conditional :repeat)
1216 (let* ((form (loop-get-form))
1217 (count (and (constantp form) ; FIXME: lexical environment constants
1218 (sb!int:constant-form-value form)))
1219 (type (cond ((not (realp count))
1220 'integer)
1221 ((plusp count)
1222 `(mod ,(1+ (ceiling count))))
1224 `(integer ,(ceiling count))))))
1225 (let ((var (loop-make-var (gensym "LOOP-REPEAT-") `(ceiling ,form) type)))
1226 (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-before-loop*)
1227 (push `(if (<= ,var 0) (go end-loop) (decf ,var)) *loop-after-body*)
1228 ;; FIXME: What should
1229 ;; (loop count t into a
1230 ;; repeat 3
1231 ;; count t into b
1232 ;; finally (return (list a b)))
1233 ;; return: (3 3) or (4 3)? PUSHes above are for the former
1234 ;; variant, L-P-B below for the latter.
1235 #+nil (loop-pseudo-body `(when (minusp (decf ,var)) (go end-loop))))))
1237 (defun loop-do-with ()
1238 (loop-disallow-conditional :with)
1239 (do ((var) (val) (dtype))
1240 (nil)
1241 (setq var (loop-pop-source)
1242 dtype (loop-optional-type var)
1243 val (cond ((loop-tequal (car *loop-source-code*) :=)
1244 (loop-pop-source)
1245 (loop-get-form))
1246 (t nil)))
1247 (loop-make-var var val dtype)
1248 (if (loop-tequal (car *loop-source-code*) :and)
1249 (loop-pop-source)
1250 (return (loop-bind-block)))))
1252 ;;;; the iteration driver
1254 (defun loop-hack-iteration (entry)
1255 (flet ((make-endtest (list-of-forms)
1256 (cond ((null list-of-forms) nil)
1257 ((member t list-of-forms) '(go end-loop))
1258 (t `(when ,(if (null (cdr (setq list-of-forms
1259 (nreverse list-of-forms))))
1260 (car list-of-forms)
1261 (cons 'or list-of-forms))
1262 (go end-loop))))))
1263 (do ((pre-step-tests nil)
1264 (steps nil)
1265 (post-step-tests nil)
1266 (pseudo-steps nil)
1267 (pre-loop-pre-step-tests nil)
1268 (pre-loop-steps nil)
1269 (pre-loop-post-step-tests nil)
1270 (pre-loop-pseudo-steps nil)
1271 (tem) (data))
1272 (nil)
1273 ;; Note that we collect endtests in reverse order, but steps in correct
1274 ;; order. MAKE-ENDTEST does the nreverse for us.
1275 (setq tem (setq data
1276 (apply (symbol-function (first entry)) (rest entry))))
1277 (and (car tem) (push (car tem) pre-step-tests))
1278 (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1279 (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1280 (setq pseudo-steps
1281 (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1282 (setq tem (cdr tem))
1283 (when *loop-emitted-body*
1284 (loop-error "iteration in LOOP follows body code"))
1285 (unless tem (setq tem data))
1286 (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1287 ;; FIXME: This (SETF FOO (NCONC FOO BAR)) idiom appears often enough
1288 ;; that it might be worth making it into an NCONCF macro.
1289 (setq pre-loop-steps
1290 (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1291 (when (car (setq tem (cdr tem)))
1292 (push (car tem) pre-loop-post-step-tests))
1293 (setq pre-loop-pseudo-steps
1294 (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1295 (unless (loop-tequal (car *loop-source-code*) :and)
1296 (setq *loop-before-loop*
1297 (list* (loop-make-desetq pre-loop-pseudo-steps)
1298 (make-endtest pre-loop-post-step-tests)
1299 (loop-make-psetq pre-loop-steps)
1300 (make-endtest pre-loop-pre-step-tests)
1301 *loop-before-loop*))
1302 (setq *loop-after-body*
1303 (list* (loop-make-desetq pseudo-steps)
1304 (make-endtest post-step-tests)
1305 (loop-make-psetq steps)
1306 (make-endtest pre-step-tests)
1307 *loop-after-body*))
1308 (loop-bind-block)
1309 (return nil))
1310 (loop-pop-source)))) ; Flush the "AND".
1312 ;;;; main iteration drivers
1314 ;;; FOR variable keyword ..args..
1315 (defun loop-do-for ()
1316 (let* ((var (loop-pop-source))
1317 (data-type (loop-optional-type var))
1318 (keyword (loop-pop-source))
1319 (first-arg nil)
1320 (tem nil))
1321 (setq first-arg (loop-get-form))
1322 (unless (and (symbolp keyword)
1323 (setq tem (loop-lookup-keyword
1324 keyword
1325 (loop-universe-for-keywords *loop-universe*))))
1326 (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP."
1327 keyword))
1328 (apply (car tem) var first-arg data-type (cdr tem))))
1330 (defun loop-when-it-var ()
1331 (or *loop-when-it-var*
1332 (setq *loop-when-it-var*
1333 (loop-make-var (gensym "LOOP-IT-") nil nil))))
1335 ;;;; various FOR/AS subdispatches
1337 ;;; ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when
1338 ;;; the THEN is omitted (other than being more stringent in its
1339 ;;; placement), and like the old "FOR x FIRST y THEN z" when the THEN
1340 ;;; is present. I.e., the first initialization occurs in the loop body
1341 ;;; (first-step), not in the variable binding phase.
1342 (defun loop-ansi-for-equals (var val data-type)
1343 (loop-make-var var nil data-type)
1344 (cond ((loop-tequal (car *loop-source-code*) :then)
1345 ;; Then we are the same as "FOR x FIRST y THEN z".
1346 (loop-pop-source)
1347 `(() (,var ,(loop-get-form)) () ()
1348 () (,var ,val) () ()))
1349 (t ;; We are the same as "FOR x = y".
1350 `(() (,var ,val) () ()))))
1352 (defun loop-for-across (var val data-type)
1353 (loop-make-var var nil data-type)
1354 (let ((vector-var (gensym "LOOP-ACROSS-VECTOR-"))
1355 (index-var (gensym "LOOP-ACROSS-INDEX-")))
1356 (multiple-value-bind (vector-form constantp vector-value)
1357 (loop-constant-fold-if-possible val 'vector)
1358 (loop-make-var
1359 vector-var vector-form
1360 (if (and (consp vector-form) (eq (car vector-form) 'the))
1361 (cadr vector-form)
1362 'vector))
1363 (loop-make-var index-var 0 'fixnum)
1364 (let* ((length 0)
1365 (length-form (cond ((not constantp)
1366 (let ((v (gensym "LOOP-ACROSS-LIMIT-")))
1367 (push `(setq ,v (length ,vector-var))
1368 *loop-prologue*)
1369 (loop-make-var v 0 'fixnum)))
1370 (t (setq length (length vector-value)))))
1371 (first-test `(>= ,index-var ,length-form))
1372 (other-test first-test)
1373 (step `(,var (aref ,vector-var ,index-var)))
1374 (pstep `(,index-var (1+ ,index-var))))
1375 (declare (fixnum length))
1376 (when constantp
1377 (setq first-test (= length 0))
1378 (when (<= length 1)
1379 (setq other-test t)))
1380 `(,other-test ,step () ,pstep
1381 ,@(and (not (eq first-test other-test))
1382 `(,first-test ,step () ,pstep)))))))
1384 ;;;; list iteration
1386 (defun loop-list-step (listvar)
1387 ;; We are not equipped to analyze whether 'FOO is the same as #'FOO
1388 ;; here in any sensible fashion, so let's give an obnoxious warning
1389 ;; whenever 'FOO is used as the stepping function.
1391 ;; While a Discerning Compiler may deal intelligently with
1392 ;; (FUNCALL 'FOO ...), not recognizing FOO may defeat some LOOP
1393 ;; optimizations.
1394 (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1395 (loop-pop-source)
1396 (loop-get-form))
1397 (t '(function cdr)))))
1398 (cond ((and (consp stepper) (eq (car stepper) 'quote))
1399 (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1400 `(funcall ,stepper ,listvar))
1401 ((and (consp stepper) (eq (car stepper) 'function))
1402 (list (cadr stepper) listvar))
1404 `(funcall ,(loop-make-var (gensym "LOOP-FN-") stepper 'function)
1405 ,listvar)))))
1407 (defun loop-for-on (var val data-type)
1408 (multiple-value-bind (list constantp list-value)
1409 (loop-constant-fold-if-possible val)
1410 (let ((listvar var))
1411 (cond ((and var (symbolp var))
1412 (loop-make-var var list data-type))
1414 (loop-make-var (setq listvar (gensym)) list 't)
1415 (loop-make-var var nil data-type)))
1416 (let ((list-step (loop-list-step listvar)))
1417 (let* ((first-endtest
1418 ;; mysterious comment from original CMU CL sources:
1419 ;; the following should use `atom' instead of `endp',
1420 ;; per [bug2428]
1421 `(atom ,listvar))
1422 (other-endtest first-endtest))
1423 (when (and constantp (listp list-value))
1424 (setq first-endtest (null list-value)))
1425 (cond ((eq var listvar)
1426 ;; The contour of the loop is different because we
1427 ;; use the user's variable...
1428 `(() (,listvar ,list-step)
1429 ,other-endtest () () () ,first-endtest ()))
1430 (t (let ((step `(,var ,listvar))
1431 (pseudo `(,listvar ,list-step)))
1432 `(,other-endtest ,step () ,pseudo
1433 ,@(and (not (eq first-endtest other-endtest))
1434 `(,first-endtest ,step () ,pseudo)))))))))))
1436 (defun loop-for-in (var val data-type)
1437 (multiple-value-bind (list constantp list-value)
1438 (loop-constant-fold-if-possible val)
1439 (let ((listvar (gensym "LOOP-LIST-")))
1440 (loop-make-var var nil data-type)
1441 (loop-make-var listvar list 'list)
1442 (let ((list-step (loop-list-step listvar)))
1443 (let* ((first-endtest `(endp ,listvar))
1444 (other-endtest first-endtest)
1445 (step `(,var (car ,listvar)))
1446 (pseudo-step `(,listvar ,list-step)))
1447 (when (and constantp (listp list-value))
1448 (setq first-endtest (null list-value)))
1449 `(,other-endtest ,step () ,pseudo-step
1450 ,@(and (not (eq first-endtest other-endtest))
1451 `(,first-endtest ,step () ,pseudo-step))))))))
1453 ;;;; iteration paths
1455 (defstruct (loop-path
1456 (:copier nil)
1457 (:predicate nil))
1458 names
1459 preposition-groups
1460 inclusive-permitted
1461 function
1462 user-data)
1464 (defun add-loop-path (names function universe
1465 &key preposition-groups inclusive-permitted user-data)
1466 (declare (type loop-universe universe))
1467 (let* ((names (sb!int:ensure-list names))
1468 (ht (loop-universe-path-keywords universe))
1469 (lp (make-loop-path
1470 :names (mapcar #'symbol-name names)
1471 :function function
1472 :user-data user-data
1473 :preposition-groups (mapcar #'sb!int:ensure-list preposition-groups)
1474 :inclusive-permitted inclusive-permitted)))
1475 (dolist (name names)
1476 (setf (gethash (symbol-name name) ht) lp))
1477 lp))
1479 ;;; Note: Path functions are allowed to use LOOP-MAKE-VAR, hack
1480 ;;; the prologue, etc.
1481 (defun loop-for-being (var val data-type)
1482 ;; FOR var BEING each/the pathname prep-phrases using-stuff... each/the =
1483 ;; EACH or THE. Not clear if it is optional, so I guess we'll warn.
1484 (let ((path nil)
1485 (data nil)
1486 (inclusive nil)
1487 (stuff nil)
1488 (initial-prepositions nil))
1489 (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1490 ((loop-tequal (car *loop-source-code*) :and)
1491 (loop-pop-source)
1492 (setq inclusive t)
1493 (unless (loop-tmember (car *loop-source-code*)
1494 '(:its :each :his :her))
1495 (loop-error "~S was found where ITS or EACH expected in LOOP iteration path syntax."
1496 (car *loop-source-code*)))
1497 (loop-pop-source)
1498 (setq path (loop-pop-source))
1499 (setq initial-prepositions `((:in ,val))))
1500 (t (loop-error "unrecognizable LOOP iteration path syntax: missing EACH or THE?")))
1501 (cond ((not (symbolp path))
1502 (loop-error
1503 "~S was found where a LOOP iteration path name was expected."
1504 path))
1505 ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1506 (loop-error "~S is not the name of a LOOP iteration path." path))
1507 ((and inclusive (not (loop-path-inclusive-permitted data)))
1508 (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1509 (let ((fun (loop-path-function data))
1510 (preps (nconc initial-prepositions
1511 (loop-collect-prepositional-phrases
1512 (loop-path-preposition-groups data)
1513 t)))
1514 (user-data (loop-path-user-data data)))
1515 (when (symbolp fun) (setq fun (symbol-function fun)))
1516 (setq stuff (if inclusive
1517 (apply fun var data-type preps :inclusive t user-data)
1518 (apply fun var data-type preps user-data))))
1519 (when *loop-named-vars*
1520 (loop-error "Unused USING vars: ~S." *loop-named-vars*))
1521 ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back).
1522 ;; Protect the system from the user and the user from himself.
1523 (unless (member (length stuff) '(6 10))
1524 (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1525 path))
1526 (do ((l (car stuff) (cdr l)) (x)) ((null l))
1527 (if (atom (setq x (car l)))
1528 (loop-make-var x nil nil)
1529 (loop-make-var (car x) (cadr x) (caddr x))))
1530 (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1531 (cddr stuff)))
1533 (defun loop-named-var (name)
1534 (let ((tem (loop-tassoc name *loop-named-vars*)))
1535 (declare (list tem))
1536 (cond ((null tem) (values (gensym) nil))
1537 (t (setq *loop-named-vars* (delete tem *loop-named-vars*))
1538 (values (cdr tem) t)))))
1540 (defun loop-collect-prepositional-phrases (preposition-groups
1541 &optional
1542 using-allowed
1543 initial-phrases)
1544 (flet ((in-group-p (x group) (car (loop-tmember x group))))
1545 (do ((token nil)
1546 (prepositional-phrases initial-phrases)
1547 (this-group nil nil)
1548 (this-prep nil nil)
1549 (disallowed-prepositions
1550 (mapcan (lambda (x)
1551 (copy-list
1552 (find (car x) preposition-groups :test #'in-group-p)))
1553 initial-phrases))
1554 (used-prepositions (mapcar #'car initial-phrases)))
1555 ((null *loop-source-code*) (nreverse prepositional-phrases))
1556 (declare (symbol this-prep))
1557 (setq token (car *loop-source-code*))
1558 (dolist (group preposition-groups)
1559 (when (setq this-prep (in-group-p token group))
1560 (return (setq this-group group))))
1561 (cond (this-group
1562 (when (member this-prep disallowed-prepositions)
1563 (loop-error
1564 (if (member this-prep used-prepositions)
1565 "A ~S prepositional phrase occurs multiply for some LOOP clause."
1566 "Preposition ~S was used when some other preposition has subsumed it.")
1567 token))
1568 (setq used-prepositions (if (listp this-group)
1569 (append this-group used-prepositions)
1570 (cons this-group used-prepositions)))
1571 (loop-pop-source)
1572 (push (list this-prep (loop-get-form)) prepositional-phrases))
1573 ((and using-allowed (loop-tequal token 'using))
1574 (loop-pop-source)
1575 (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1576 (when (cadr z)
1577 (if (setq tem (loop-tassoc (car z) *loop-named-vars*))
1578 (loop-error
1579 "The variable substitution for ~S occurs twice in a USING phrase,~@
1580 with ~S and ~S."
1581 (car z) (cadr z) (cadr tem))
1582 (push (cons (car z) (cadr z)) *loop-named-vars*)))
1583 (when (or (null *loop-source-code*)
1584 (symbolp (car *loop-source-code*)))
1585 (return nil))))
1586 (t (return (nreverse prepositional-phrases)))))))
1588 ;;;; master sequencer function
1590 (defun loop-sequencer (indexv indexv-type
1591 variable variable-type
1592 sequence-variable sequence-type
1593 step-hack default-top
1594 prep-phrases)
1595 (let ((endform nil) ; form (constant or variable) with limit value
1596 (sequencep nil) ; T if sequence arg has been provided
1597 (testfn nil) ; endtest function
1598 (test nil) ; endtest form
1599 (stepby (1+ (or (loop-typed-init indexv-type) 0))) ; our increment
1600 (stepby-constantp t)
1601 (step nil) ; step form
1602 (dir nil) ; direction of stepping: NIL, :UP, :DOWN
1603 (inclusive-iteration nil) ; T if include last index
1604 (start-given nil) ; T when prep phrase has specified start
1605 (start-value nil)
1606 (start-constantp nil)
1607 (limit-given nil) ; T when prep phrase has specified end
1608 (limit-constantp nil)
1609 (limit-value nil))
1610 (flet ((assert-index-for-arithmetic (index)
1611 (unless (atom index)
1612 (loop-error "Arithmetic index must be an atom."))))
1613 (when variable (loop-make-var variable nil variable-type))
1614 (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1615 (setq prep (caar l) form (cadar l))
1616 (case prep
1617 ((:of :in)
1618 (setq sequencep t)
1619 (loop-make-var sequence-variable form sequence-type))
1620 ((:from :downfrom :upfrom)
1621 (setq start-given t)
1622 (cond ((eq prep :downfrom) (setq dir ':down))
1623 ((eq prep :upfrom) (setq dir ':up)))
1624 (multiple-value-setq (form start-constantp start-value)
1625 (loop-constant-fold-if-possible form indexv-type))
1626 (assert-index-for-arithmetic indexv)
1627 ;; KLUDGE: loop-make-var generates a temporary symbol for
1628 ;; indexv if it is NIL. We have to use it to have the index
1629 ;; actually count
1630 (setq indexv (loop-make-var indexv form indexv-type)))
1631 ((:upto :to :downto :above :below)
1632 (cond ((loop-tequal prep :upto) (setq inclusive-iteration
1633 (setq dir ':up)))
1634 ((loop-tequal prep :to) (setq inclusive-iteration t))
1635 ((loop-tequal prep :downto) (setq inclusive-iteration
1636 (setq dir ':down)))
1637 ((loop-tequal prep :above) (setq dir ':down))
1638 ((loop-tequal prep :below) (setq dir ':up)))
1639 (setq limit-given t)
1640 (multiple-value-setq (form limit-constantp limit-value)
1641 (loop-constant-fold-if-possible form `(and ,indexv-type real)))
1642 (setq endform (if limit-constantp
1643 `',limit-value
1644 (loop-make-var
1645 (gensym "LOOP-LIMIT-") form
1646 `(and ,indexv-type real)))))
1647 (:by
1648 (multiple-value-setq (form stepby-constantp stepby)
1649 (loop-constant-fold-if-possible form
1650 `(and ,indexv-type (real (0)))))
1651 (unless stepby-constantp
1652 (loop-make-var (setq stepby (gensym "LOOP-STEP-BY-"))
1653 form
1654 `(and ,indexv-type (real (0)))
1655 t)))
1656 (t (loop-error
1657 "~S invalid preposition in sequencing or sequence path;~@
1658 maybe invalid prepositions were specified in iteration path descriptor?"
1659 prep)))
1660 (when (and odir dir (not (eq dir odir)))
1661 (loop-error
1662 "conflicting stepping directions in LOOP sequencing path"))
1663 (setq odir dir))
1664 (when (and sequence-variable (not sequencep))
1665 (loop-error "missing OF or IN phrase in sequence path"))
1666 ;; Now fill in the defaults.
1667 (cond ((not start-given)
1668 ;; default start
1669 ;; DUPLICATE KLUDGE: loop-make-var generates a temporary
1670 ;; symbol for indexv if it is NIL. See also the comment in
1671 ;; the (:from :downfrom :upfrom) case
1672 (assert-index-for-arithmetic indexv)
1673 (setq indexv
1674 (loop-make-var
1675 indexv
1676 (setq start-constantp t
1677 start-value (or (loop-typed-init indexv-type) 0))
1678 `(and ,indexv-type real))))
1679 (limit-given
1680 ;; if both start and limit are given, they had better both
1681 ;; be REAL. We already enforce the REALness of LIMIT,
1682 ;; above; here's the KLUDGE to enforce the type of START.
1683 (flet ((type-declaration-of (x)
1684 (and (eq (car x) 'type) (caddr x))))
1685 (let ((decl (find indexv *loop-declarations*
1686 :key #'type-declaration-of))
1687 (%decl (find indexv *loop-declarations*
1688 :key #'type-declaration-of
1689 :from-end t)))
1690 (sb!int:aver (eq decl %decl))
1691 (when decl
1692 (setf (cadr decl)
1693 `(and real ,(cadr decl))))))))
1694 (cond ((member dir '(nil :up))
1695 (when (or limit-given default-top)
1696 (unless limit-given
1697 (loop-make-var (setq endform (gensym "LOOP-SEQ-LIMIT-"))
1699 indexv-type)
1700 (push `(setq ,endform ,default-top) *loop-prologue*))
1701 (setq testfn (if inclusive-iteration '> '>=)))
1702 (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1703 (t (unless start-given
1704 (unless default-top
1705 (loop-error "don't know where to start stepping"))
1706 (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1707 (when (and default-top (not endform))
1708 (setq endform (loop-typed-init indexv-type)
1709 inclusive-iteration t))
1710 (when endform (setq testfn (if inclusive-iteration '< '<=)))
1711 (setq step
1712 (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1713 (when testfn
1714 (setq test
1715 `(,testfn ,indexv ,endform)))
1716 (when step-hack
1717 (setq step-hack
1718 `(,variable ,step-hack)))
1719 (let ((first-test test) (remaining-tests test))
1720 ;; As far as I can tell, the effect of the following code is
1721 ;; to detect cases where we know statically whether the first
1722 ;; iteration of the loop will be executed. Depending on the
1723 ;; situation, we can either:
1724 ;; a) save one jump and one comparison per loop (not per iteration)
1725 ;; when it will get executed
1726 ;; b) remove the loop body completely when it won't be executed
1728 ;; Noble goals. However, the code generated in case a) will
1729 ;; fool the loop induction variable detection, and cause
1730 ;; code like (LOOP FOR I TO 10 ...) to use generic addition
1731 ;; (bug #278a).
1733 ;; Since the gain in case a) is rather minimal and Python is
1734 ;; generally smart enough to handle b) without any extra
1735 ;; support from the loop macro, I've disabled this code for
1736 ;; now. The code and the comment left here in case somebody
1737 ;; extends the induction variable bound detection to work
1738 ;; with code where the stepping precedes the test.
1739 ;; -- JES 2005-11-30
1740 #+nil
1741 (when (and stepby-constantp start-constantp limit-constantp
1742 (realp start-value) (realp limit-value))
1743 (when (setq first-test
1744 (funcall (symbol-function testfn)
1745 start-value
1746 limit-value))
1747 (setq remaining-tests t)))
1748 `(() (,indexv ,step)
1749 ,remaining-tests ,step-hack () () ,first-test ,step-hack)))))
1751 ;;;; interfaces to the master sequencer
1753 (defun loop-for-arithmetic (var val data-type kwd)
1754 (loop-sequencer
1755 var (loop-check-data-type data-type 'number)
1756 nil nil nil nil nil nil
1757 (loop-collect-prepositional-phrases
1758 '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1759 nil (list (list kwd val)))))
1762 ;;;; builtin LOOP iteration paths
1765 (loop for v being the hash-values of ht do (print v))
1766 (loop for k being the hash-keys of ht do (print k))
1767 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1768 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1771 (defun loop-hash-table-iteration-path (variable data-type prep-phrases
1772 &key (which (sb!int:missing-arg)))
1773 (declare (type (member :hash-key :hash-value) which))
1774 (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1775 (loop-error "too many prepositions!"))
1776 ((null prep-phrases)
1777 (loop-error "missing OF or IN in ~S iteration path")))
1778 (let ((ht-var (gensym "LOOP-HASHTAB-"))
1779 (next-fn (gensym "LOOP-HASHTAB-NEXT-"))
1780 (dummy-predicate-var nil)
1781 (post-steps nil))
1782 (multiple-value-bind (other-var other-p)
1783 (loop-named-var (ecase which
1784 (:hash-key 'hash-value)
1785 (:hash-value 'hash-key)))
1786 ;; @@@@ LOOP-NAMED-VAR returns a second value of T if the name
1787 ;; was actually specified, so clever code can throw away the
1788 ;; GENSYM'ed-up variable if it isn't really needed. The
1789 ;; following is for those implementations in which we cannot put
1790 ;; dummy NILs into MULTIPLE-VALUE-SETQ variable lists.
1791 (setq other-p t
1792 dummy-predicate-var (loop-when-it-var))
1793 (let* ((key-var nil)
1794 (val-var nil)
1795 (variable (or variable (gensym "LOOP-HASH-VAR-TEMP-")))
1796 (bindings `((,variable nil ,data-type)
1797 (,ht-var ,(cadar prep-phrases))
1798 ,@(and other-p other-var `((,other-var nil))))))
1799 (ecase which
1800 (:hash-key (setq key-var variable
1801 val-var (and other-p other-var)))
1802 (:hash-value (setq key-var (and other-p other-var)
1803 val-var variable)))
1804 (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1805 (when (or (consp key-var) data-type)
1806 (setq post-steps
1807 `(,key-var ,(setq key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1808 ,@post-steps))
1809 (push `(,key-var nil) bindings))
1810 (when (or (consp val-var) data-type)
1811 (setq post-steps
1812 `(,val-var ,(setq val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1813 ,@post-steps))
1814 (push `(,val-var nil) bindings))
1815 `(,bindings ;bindings
1816 () ;prologue
1817 () ;pre-test
1818 () ;parallel steps
1819 (not (multiple-value-setq (,dummy-predicate-var ,key-var ,val-var)
1820 (,next-fn))) ;post-test
1821 ,post-steps)))))
1823 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases
1824 &key symbol-types)
1825 (cond ((and prep-phrases (cdr prep-phrases))
1826 (loop-error "Too many prepositions!"))
1827 ((and prep-phrases (not (member (caar prep-phrases) '(:in :of))))
1828 (sb!int:bug "Unknown preposition ~S." (caar prep-phrases))))
1829 (unless (symbolp variable)
1830 (loop-error "Destructuring is not valid for package symbol iteration."))
1831 (let ((pkg-var (gensym "LOOP-PKGSYM-"))
1832 (next-fn (gensym "LOOP-PKGSYM-NEXT-"))
1833 (variable (or variable (gensym "LOOP-PKGSYM-VAR-")))
1834 (package (or (cadar prep-phrases) '*package*)))
1835 (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types))
1836 *loop-wrappers*)
1837 `(((,variable nil ,data-type) (,pkg-var ,package))
1841 (not (multiple-value-setq (,(loop-when-it-var)
1842 ,variable)
1843 (,next-fn)))
1844 ())))
1846 ;;;; ANSI LOOP
1848 (defun make-ansi-loop-universe ()
1849 (let ((w (make-standard-loop-universe
1850 :keywords '((named (loop-do-named))
1851 (initially (loop-do-initially))
1852 (finally (loop-do-finally))
1853 (do (loop-do-do))
1854 (doing (loop-do-do))
1855 (return (loop-do-return))
1856 (collect (loop-list-collection list))
1857 (collecting (loop-list-collection list))
1858 (append (loop-list-collection append))
1859 (appending (loop-list-collection append))
1860 (nconc (loop-list-collection nconc))
1861 (nconcing (loop-list-collection nconc))
1862 (count (loop-sum-collection count
1863 ;; This could be REAL, but when
1864 ;; combined with SUM, it has to be
1865 ;; NUMBER.
1866 number
1867 fixnum))
1868 (counting (loop-sum-collection count
1869 number
1870 fixnum))
1871 (sum (loop-sum-collection sum number number))
1872 (summing (loop-sum-collection sum number number))
1873 (maximize (loop-maxmin-collection max))
1874 (minimize (loop-maxmin-collection min))
1875 (maximizing (loop-maxmin-collection max))
1876 (minimizing (loop-maxmin-collection min))
1877 (always (loop-do-always t nil)) ; Normal, do always
1878 (never (loop-do-always t t)) ; Negate test on always.
1879 (thereis (loop-do-thereis t))
1880 (while (loop-do-while nil :while)) ; Normal, do while
1881 (until (loop-do-while t :until)) ;Negate test on while
1882 (when (loop-do-if when nil)) ; Normal, do when
1883 (if (loop-do-if if nil)) ; synonymous
1884 (unless (loop-do-if unless t)) ; Negate test on when
1885 (with (loop-do-with))
1886 (repeat (loop-do-repeat)))
1887 :for-keywords '((= (loop-ansi-for-equals))
1888 (across (loop-for-across))
1889 (in (loop-for-in))
1890 (on (loop-for-on))
1891 (from (loop-for-arithmetic :from))
1892 (downfrom (loop-for-arithmetic :downfrom))
1893 (upfrom (loop-for-arithmetic :upfrom))
1894 (below (loop-for-arithmetic :below))
1895 (above (loop-for-arithmetic :above))
1896 (to (loop-for-arithmetic :to))
1897 (upto (loop-for-arithmetic :upto))
1898 (downto (loop-for-arithmetic :downto))
1899 (by (loop-for-arithmetic :by))
1900 (being (loop-for-being)))
1901 :iteration-keywords '((for (loop-do-for))
1902 (as (loop-do-for)))
1903 :type-symbols '(array atom bignum bit bit-vector character
1904 compiled-function complex cons double-float
1905 fixnum float function hash-table integer
1906 keyword list long-float nil null number
1907 package pathname random-state ratio rational
1908 readtable sequence short-float simple-array
1909 simple-bit-vector simple-string simple-vector
1910 single-float standard-char stream string
1911 base-char symbol t vector)
1912 :type-keywords nil)))
1913 (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
1914 :preposition-groups '((:of :in))
1915 :inclusive-permitted nil
1916 :user-data '(:which :hash-key))
1917 (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
1918 :preposition-groups '((:of :in))
1919 :inclusive-permitted nil
1920 :user-data '(:which :hash-value))
1921 (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
1922 :preposition-groups '((:of :in))
1923 :inclusive-permitted nil
1924 :user-data '(:symbol-types (:internal
1925 :external
1926 :inherited)))
1927 (add-loop-path '(external-symbol external-symbols)
1928 'loop-package-symbols-iteration-path w
1929 :preposition-groups '((:of :in))
1930 :inclusive-permitted nil
1931 :user-data '(:symbol-types (:external)))
1932 (add-loop-path '(present-symbol present-symbols)
1933 'loop-package-symbols-iteration-path w
1934 :preposition-groups '((:of :in))
1935 :inclusive-permitted nil
1936 :user-data '(:symbol-types (:internal
1937 :external)))
1940 (defparameter *loop-ansi-universe*
1941 (make-ansi-loop-universe))
1943 (defun loop-standard-expansion (keywords-and-forms environment universe)
1944 (if (and keywords-and-forms (symbolp (car keywords-and-forms)))
1945 (loop-translate keywords-and-forms environment universe)
1946 (let ((tag (gensym)))
1947 `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
1949 (sb!int:defmacro-mundanely loop (&environment env &rest keywords-and-forms)
1950 (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))
1952 (sb!int:defmacro-mundanely loop-finish ()
1953 #!+sb-doc
1954 "Cause the iteration to terminate \"normally\", the same as implicit
1955 termination by an iteration driving clause, or by use of WHILE or
1956 UNTIL -- the epilogue code (if any) will be run, and any implicitly
1957 collected result will be returned as the value of the LOOP."
1958 '(go end-loop))