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